How can I get my image to display using django? - python

I cannot get my images to display on my webpage while using Django. All I see is the images 'alt' text displayed, and a broken image icon next to it. I'm able to successfully upload the image as originally intended. I'm using an Ubuntu AWS instance with Apache installed on it for my server. I also have Pillow installed for displaying images.
I'm also able to successfully load my CSS, so I know that it probably isn't an issue with my static directories or settings.
This is my settings.py file:
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)zp1^v$1v9%#3e*rz4yp0o964-^!8#ruff4$((b5vcv6*h#d-x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product.apps.ProductConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'productapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'productapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static') # project level
STATIC_URL = 'static/'
# STATICFILES_DIRS = ['/var/www/productapp/static/']
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'
My urls.py file:
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path, include
def home(request):
return HttpResponse("Home page")
urlpatterns = [
path('', TemplateView.as_view(template_name="index.html"), name="index"),
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('productapp/', include('product.urls', namespace='product'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Since I'm using Apache I've tried editing the apache2.conf file to point to a specified media folder as follows:
Alias /media/ /var/www/prodictapp/media/
Alias /static /var/www/productapp/static/
<Directory /var/www/productapp/static>
Require all granted
</Directory>
<Directory /var/www/productapp/media>
Require all granted
</Directory>
WSGIScriptAlias / /var/www/productapp/productapp/wsgi.py
WSGIPythonPath /var/www/productapp
<Directory /var/www/productapp/productapp>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Template:
{% extends 'product/base.html' %}
{% block title %}{{ product.name }} - Details{% endblock %}
{% block body %}
<h3>Details for {{ product.name }}:</h3>
<p>
Name: {{ product.name }}<br>
Price: ${{ product.price }}<br>
Description: {{ product.description }}<br>
Quantity: {{ product.quantity }}<br>
{% if product.image %} {# If record has image, display it #}
Product image: <br><img src="{{ product.image.url }}" alt="{{ product.name }}"><br>
{% endif %}
</p>
{% endblock %}

You can try out this
<img src="{% static product.image.url %}" /> # use this
<img src="{{ MEDIA_URL }}{{ product.image.url}}" /> # or this

Related

After I submit form with uploading photos, there are nothing to save on Django database

I met a problem.
When I choose a photo as a profile_pic on the registration page,
it saves any information without a photo.
But I can't find out why it didn't work.
There is nothing in the Profile pic after submitting.
setting.py
"""
Django settings for learning_templates project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
MEDIA_DIR=os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pgmh_#pcqd(3sf(a3oj#^vyv4l-#p6g=n-=^!z)0d#!k)!_ear'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'basic_app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'learning_templates.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'learning_templates.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
PASSWORD_HASHERS=[
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS':{'min_length':9}
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=[STATIC_DIR,]
#MEDIA
MEDIA_ROOT=MEDIA_DIR
MEDIA_URL='/media/'
LOGIN_URL='basic_app/user_login'
in views.py: register
def register(request):
registered= False
logging.error(request.method)
if request.method == 'POST':
user_form= UserForm(data=request.POST)
profile_form=UserProfileInfoForm(request.POST)
logging.error(user_form)
if user_form.is_valid() and profile_form.is_valid():
user=user_form.save()
user.set_password(user.password)
user.save()
profile=profile_form.save(commit=False)
profile.user=user
if 'profile_pics' in request.FILES:
profile.profile_pic=request.FILES['profile_pics']
profile.save()
registered=True
else:
print(user_form.errors,profile_form.errors)
else:
user_form=UserForm()
profile_form=UserProfileInfoForm()
return render(request,'basic_app/registeration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
# additional
portfolio_site=models.URLField(blank=True)
profile_pic = models.ImageField(upload_to = 'profile_pics', blank = True)
def __str__(self):
return self.user.username
forms.py
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model=UserProfileInfo
fields=('portfolio_site','profile_pic')
registeration.html
<!DOCTYPE html>
{% extends "basic_app/base.html" %}
{% load static %}
{% block body_block %}
{{registered }}
<div class=jumbotron>
<h1>Test Register</h1>
{% if registered %}
<h1>Thank you for Register</h1>
{% else %}
<h1>Register Here</h1>
<h3>
<h1>Fill out the form</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p}}
{{ profile_form.as_p }}
<input type="submit" name="" value="Register">
</form>
</h3>
{% endif %}
</div>
{% endblock %}
And I have made sure that the profile_pics folder has nothing.
I don't know where I am wrong or what I miss but anything without a photo has saved.
If anything misses, please tell me.
Thank you for your time.
First check if the uploaded images is in your media/profile_pics folder.
Since you are viewing the data uploaded using the django admin panel ,it does not shows the actual image it will show the image name.
Try to display the image in a template by passing the user content in the context section while sending the rendering the template.

static files in the media folder not showing when i upload on live server

Hey guys sorry to bother you, I'm new to django and I made a personal portfolio and locally everything is perfect but the deployed one is not loading the images that I upload on the live app.
I tried to see youtube videos a lot of topics over here and I cant find a solution...:(
Heres my code:
settings.py
import os
import django_heroku
from decouple import config
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['***********']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'portfolio',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'my_portfolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'my_portfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_TMP = os.path.join(BASE_DIR, 'static')
os.makedirs(STATIC_TMP, exist_ok=True)
os.makedirs(STATIC_ROOT, exist_ok=True)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
django_heroku.settings(locals())
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from portfolio import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=250)
image = models.ImageField(upload_to='portfolio/images')
url = models.URLField(blank=True)
def __str__(self):
return self.title
home.html
{% extends "portfolio/base.html" %}
{% load static %}
{% block content %}
<div class="row justify-content-center my-3">
<div class="col-5">
<img src="{% static 'portfolio/pic_me.jpg' %}" class="img-fluid">
</div>
</div>
<div class="row justify-content-center mb-3">
<div class="col-md-9 text-center">
<h1 id="hometext" class="font-weight-bold">Hello</h1>
</div>
</div>
<h2 class="mt-5">Portfolio</h2>
<hr>
<div class="row">
{% for project in projects %}
<div class="col-lg-4 col-md-6">
{% if project.url %}
<a href="{{ project.url }}">
<img src="{{ project.image.url }}" class="img-fluid mb-2">
</a>
{% else %}
<img src="{{ project.image.url }}" class="img-fluid mb-2">
{% endif %}
<div class="textport">
<h3>{{ project.title }}</h3>
<p>{{ project.description }}</p>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Serving media and static files by django in live server and prod is discouraged from the developer themselves, it only should be used when in debug mode.
As for your bug, did you try accessing /media/portfolio/images/uploaded_image and see if it shows an uploaded image ?
Also verify the path of your static folder my_app/static/my_app/example.jpg
The doc may help: https://docs.djangoproject.com/en/2.2/howto/static-files/

Django NoReverseMatch Reverse for 'cart-add' with arguments '('',)' not found

I am getting the following error after I added href="{% url 'cart-add' product.id %}" to the add to cart button on my product.html file:
NoReverseMatch at /3/
Reverse for 'cart-add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[0-9]+)\\/$']
I believe that it's a urls pathing problem or settings, but I'm not sure how to resolve it. In case there are relevant files I missed displaying here, here is my github: https://github.com/sebapaik/django-shop
My product.html file looks like this:
{% extends "shop/base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-4">
<img class="img-thumbnail" src="{{ object.imageurl }}" alt="">
</div>
<div class="col-lg-8">
<h2>{{ object.brand }} {{ object.pname }}</h2>
<p>${{ object.price }}</p>
<p>{{ object.description }}</p>
**likely the problem below**
<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' product.id %}">Add to cart</button>
</div>
</div>
{% endblock content %}
My Project/urls.py (main) looks like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('shop.urls')),
path('cart/', include('cart.urls')),
]
My shop/urls.py looks like this:
from django.urls import path
from .views import ProductListView, ProductDetailView
from . import views
urlpatterns = [
path('', ProductListView.as_view(), name = 'shop-index'),
path('<int:pk>/', ProductDetailView.as_view(), name = 'shop-product'),
]
My cart/urls.py looks like this:
from django.urls import path
from . import views
urlpatterns = [
path('add/<int:product_id>/', views.add_cart, name='cart-add'),
path('', views.cart_detail, name='cart-detail'),
]
My settings.py looks like this:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#9k!nb!1wi5*d=+*#3j+$gl%(#$z(c1aqsyh1p+qqs#)yeuh*_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'shop.apps.ShopConfig',
'cart.apps.CartConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'Project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
I am using Django 2.1.1, Python 3.6, and Windows 10
Your product.id is empty according to the error message. You should use object.id instead in your template:
<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' object.id %}">Add to cart</button>
It seems that Django recognise your request url is '/3/', what you want to reverse is 'car/add/3/', you could try simply use [href="/cart-add/{{product.id}}'"] to replace [href="{% url 'cart-add' product.id %}"].By the way, while your 'shop/urls.py' and 'cart/urls.py' has the same line "path('add//', views.add_cart, name='cart-add'),"? It may lead to some other problems.

django avatar custom template directory

I have a new problem with django avatar, can i change template base of django avatar in template custom on my project ?
my current template :
{% extends "templates/base.html" %}
{% load i18n avatar_tags %}
{% block content %}
<p>Your current avatar :</p>
{% avatar user %}
{% if not avatars %}
<p>{% trans "You haven't uploaded an avatar yet. Please upload one now." %}</p>
{% else %}
<form method="POST" action="{% url 'avatar_change' %}">
<ul>
{{ primary_avatar_form.as_ul }}
</ul>
<p>{% csrf_token %}<input type="submit" value="{% trans "Choose new Default" %}" /></p>
</form>
{% endif %}
<form enctype="multipart/form-data" method="POST" action="{% url 'avatar_add' %}">
{{ upload_avatar_form.as_p }}
<p>{% csrf_token %}<input type="submit" value="{% trans "Upload New Image" %}" /></p>
</form>
{% endblock %}
I copy/paste the avatar template directory in my project and the change not work.
EDIT :
My Django version is 1.9.8
Is my settings.py :
""""
# -*- coding: utf-8 -*- """ Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """
import os from django.core.mail import send_mail
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print "base dir path :", BASE_DIR
# resultat du print => /home/cpoudevigne/Projets/MyMemoryBox/mysite
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fywfd7s#e%36b_g#%!lt3o$t6i5g(&pfa8f9aa5#fhe#%7dzh('
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = True
ALLOWED_HOSTS = []
# Grappelli settings
GRAPPELLI_ADMIN_TITLE = "My Title"
# Application definition
INSTALLED_APPS = [
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'avatar',
'registration',
'mymemoryapp', ]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
}, ]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
} }
# Django-registration settings ACCOUNT_ACTIVATION_DAYS = 7 LOGIN_REDIRECT_URL = '/'
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
}, ]
# Django-mail Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' DEFAULT_FROM_EMAIL = ''
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_DIR = os.path.dirname(__file__) print "PROJECT_DIR :", PROJECT_DIR
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'mysite', 'static') STATIC_URL
= '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'static/'), ) print 'STATICFILES_DIRS :', STATICFILES_DIRS
If you want to override django-avatar's change page, you should place template you present in <appname>/templates/avatar/change.html or <templates_dir>/avatar/change.html if you have configured one.

Django/Python staticfiles is not loading

mysite/settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0hmrsl%ivudj7qe9+nz5l2w#s=op1urz_8*l5*)pv0+1d-j#^2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
Everything looks fine. I'm not sure why it wont link up to my css. Looks like it can't find my static folder along with the stylesheet.
polls/templates/polls/index.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available</p>
{% endif %}
polls/static/polls/style.css
li a {
color: red;
}
From your settings.py that you posted you haven't set your STATIC_ROOT and from this I'm assuming you also haven't configured your urls.py for your static files either.
You can check out the documentation for how to set this up.

Categories