Django can't find images and static files - django

I use django and my site works perfect but cant load images. I guess wrong thing is paths but i can't fix it. I see questions like that and apply all of them to my site but they did not work, please someone help me, i can't solve that for a few days.
NOTE : my site works fine on localhost, on my computer but don't work on server

Create a folder called static in your project directory or your app directory. Create another folder inside static called images.
In your settings.py file, add this line.
STATIC_URL = '/static/'
In your template file add this to the first line.
{% load static %}
In your template, use code like this to get the image to show.
<img src="{% static "image/example.jpg" %}"/>
Add the following lines in settings.py.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
Finally go to your server project folder and use the following command.
python manage.py collectstatic
This command will copy all static files (e.g. images) from you static folders and paste it in folder you mentioned in STATIC_ROOT, in this case the folder is staticfiles.
Hope this helps.

Not sure if this is still of interest, but have been having the same problem and I had to do some searching. Here is the solution (https://docs.djangoproject.com/en/3.2/howto/static-files/deployment/ )
My understanding is that STATIC_ROOT acts as a "management repository" after you run collectstatic, and Django doesn't serve the files from there. You need to set up a separate folder. This is because in production, as flagged above, the suggestion is to have a separate server dedicated to such files.
In my case, I just created a separate folder next to static,
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'),)
Note, that this is NOT THE RECOMMENDED PLACE to PUT IT, and the above STATICFILES_DIRS should be separate, OUTSIDE your project folder/on a separate server. I put it there as my project was small, for testing purposes.
As flagged in the official documents too, you need to run collectstatic everytime a file there changes, and AFTER THAT you need to COPY THE FILES to the directory from where they are actually served, ie the directory that DJANGO is actually reading.
No changes are needed to the template(s).
Small add-on: the above is necessary (at least I found it so) for media/image files. Does not apply to the css/js files, which work just fine out of the normal '/static/' folder. Wanted to add this as I found LOTS of guides/explanations about setting up this '/static/' folder and collect static, but almost none about taking the additional step of moving images to a separate folder, STATICFILES_DIRS (or whatever name you want to set).

it is not about path, i guess. Becuse here is another basic project
enter image description here
views
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1><img src='static/ben2.jpg'></h1>")
settings.py
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.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'key
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['my_server_ip']
# Application definition
INSTALLED_APPS = [
'webapp',
'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 = 'web.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 = 'web.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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.11/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.11/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.11/howto/static-files/
STATIC_URL = '/static/'
I have tried all combinations like what you said :D but they did not help me

Below STATIC_URL line, insert this :
STATIC_ROOT = os.join.path(BASE_DIR, 'static')

Related

Hosting Static Files on Amazon Web Services > Amazon Bucket - Django - PNG - CSS files

I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. I have followed so many tutorials and started from scratch so many times and nothing is seeming to work. Thank You so much in advance.What is wrong with the configuration below? Is MEDIA_URL affecting it?
P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine.
import django_heroku
from pathlib import Path
import os
from django_quill import quill
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ROOT_DIR = os.path.dirname(BASE_DIR)
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
#MEDIA_ROOT = os.path.join(BAS_DIR, 'media')
TIME_INPUT_FORMATS = ['%I:%M %p',]
#Media_URL = '/signup/front_page/sheets/'
# 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 = 'HERE BUT NOT SHOWN'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
#ADMIN_USERNAME = 'HERE BUT NOT SHOWN'
#ADMIN_PASSWORD = 'HERE BUT NOT SHOWN'
#AUTHENTICATION_BACKENDS = [
# 'django.contrib.auth.backends.ModelBackend',
# 'config.backends.SettingsBackend',
#]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
'django_quill',
'tinymce',
'ckeditor',
'boto3',
#'django_extensions',
'storages',
#'django-storages',
'django_filters',
]
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 = 'inspect_list.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'DIRS': [os.path.join(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 = 'inspect_list.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.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/3.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',
},
]
AWS_ACCESS_KEY_ID = 'HERE BUT NOT SHOWN'
AWS_SECRET_ACCESS_KEY = 'HERE BUT NOT SHOWN'
AWS_STORAGE_BUCKET_NAME = 'name1234'
AWS_S3_CUSTOM_DOMAIN = 'name1234.s3.amazonaws.com'
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = 'https://name1234.s3.amazonaws.com/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
#AWS_S3_FILE_OVERWRITE = False
#AWS_DEFAULT_ACL = None
#DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
#STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
#STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
#STATIC_URL = '/static/'
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Cancun'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
AUTH_USER_MODEL = 'my_app.CustomUser'
LOGIN_REDIRECT_URL = 'front_page'
LOGOUT_REDIRECT_URL = 'login'
django_heroku.settings(locals())
The question is not clear. You're asking about static resources but the code you have shared is of Django and Heroku? How come Python / Django can be static? Which URL you're using to load your website? If you're using localhost then it can't be from S3 and if it's s3 URL then it can't be local.
Another problem I can guess is hardcoded wrong paths in static assets. You have to make all your paths "relative" for static S3 website hosting to work.
Another solution is to use CloudFront in front of S3 to route dynamic contents of your website to your Django application. You can host your Django app on Heruko or EC2 or ECS/EKS, etc. So 1 origin for S3 and 2nd origin for your python code.

Django serves CSS files and Favicon but not images from root static when debug =false or in production

I have been working on a personal profile site and have an image for my cover page saved in my root static folder. I can see the cover image fine in the browser when debug is true but when debug is false or I am in production the file is a 404 error, nowhere to be found.
The root directory also has a CSS file (style.css) and a favicon.ico which both show up fine when debug is set to false or I am in production, it is just the image that doesn't show/work.
I also have a background image in the "Polls" app that shows up fine in both debug=false and production.
Here is an image of my file directory:
Here is my settings.py which, based on Django documentation and Heroku deployment documentation, should be configured correctly:
import os
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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'NUNYABIZNESS'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))
ALLOWED_HOSTS = [
'still-atoll-90110.herokuapp.com',
'localhost',
'www.dominicscotto.org',
]
# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'polls.apps.PollsConfig',
'projects.apps.ProjectsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'myportfolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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 = 'myportfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
DATABASES = { 'default': dj_database_url.config(conn_max_age=600)}
# Password validation
# https://docs.djangoproject.com/en/1.11/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.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = None
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
I tried calling the image from both the css:
body {
background: white url("images/Cover_image.jpeg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
and the head of the base.html:
<style> body { background-image: url(images/Cover_image.jpeg);} </style>
But it doesn't seem to be an issue with how I am calling for the image, it just isn't there in the browser.
When I run collectstatic it seems to be finding and grouping the files in "staticfiles" correctly:
Directory showing statifiles
I believe it has something to do with the image being in the root static folder but I am not clear why Django doesn't like it there vs. in a specific app. Any help would be greatly appreciated.
I am using Django 2.1 and Python 3.7.0
as in official documentation:
In your templates, use the static template tag to build the URL
for the given relative path using the configured STATICFILES_STORAGE.
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
and I think that in css you must use real path, Django doesn't serve css files with django template system. In your example, it would be
body {
background: white url("static/images/Cover_image.jpeg");
...
}
also, you can check the availability of your static files on production just use right path, that will start with static/ in your case.
Solved: Cover_Image.jpeg has a capital I in image which was not what I had in my css or head file. A case of missed capitalization due to bad naming convention.
I have changed Cover_Image.jpeg to cover_image.jpeg and in my CSS I'm using:
background: white url("images/cover_image.jpeg");
I also had to run:
python manage.py collectstatic --clear
for Django to catch these static files with Debug set to false

Django - Static images do not load, throw 404 error in console

I've been trying to solve this error for a very long time. I have a lot of static images that I am trying to open through my website. However, none of the static images will load, and when I look in the console, I see the error Failed to load resource: the server responded with a status of 404 (Not Found)
Does anyone know why this is happening? I have ran collectstatic multiple times, restarted the server, done everything.
urls.py
from django.contrib import admin
from django.urls import path
import posts.views
import sitepages.views
import hackathons.views
import projects.views
import skills.views
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
#path('blog/', posts.views.blog, name = "blog"),
#path('posts/<int:post_id>/', posts.views.post_details, name="post_details"),
path('about/', sitepages.views.about,name="about"),
path('awards/',sitepages.views.awards,name="awards"),
path('skills/',skills.views.skills,name="skills"),
path('skills/<int:skill_id>/', skills.views.skill_details,name="skill_details"),
path('projects/',projects.views.project,name="projects"),
path('hackathons/',hackathons.views.hackathons,name="hackathons"),
path('',sitepages.views.home,name="home"),
#path('hobbies/',sitepages.views.hobbies,name="hobbies"),
path('internships/',sitepages.views.internships,name="internships"),
path('project_details/<int:project_id>/', projects.views.project_details,name="project_details"),
path('hackathon_details/<int:hackathon_id>/', hackathons.views.hackathon_details, name="hackathon_details")
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Static section of settings.py
"""
Django settings for pranavblog project.
Generated by 'django-admin startproject' using Django 2.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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__)))
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'posts',
'sitepages',
'hackathons',
'projects',
'pagedown',
'skills.apps.SkillsConfig',
'django.forms'
]
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
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 = 'pranavblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(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 = 'pranavblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.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/2.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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Above is the whole settings.py, as requested. Allowed hosts and secret key were left out on purpose.
Please let me know if you need more information.
Edit:
Here is my project folder structure. The media folder contains a lot of images.
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
You've added a path to serve MediaFiles, not Static Files. You might want to add static(settings. STATIC_URL,document_root=settings. STATIC_ROOT) to your urls.py
Do not use DEBUG=True in production, that is a big "No".
Have you considered using a proxy like NGINX ? You'll be able to cache your static files improving perfomance. Django is not designed to serve Static files.
I believe you're missing this:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
Or maybe not, but that's the only thing I can see you don't have in your settings.

Not able to refer static files of Django project from Heroku

I am unable to load static files in production, whereas they work on local machine.
I have followed the steps in https://devcenter.heroku.com/articles/django-assets
as well as the existing answers but I am not able to make it run. I am overlooking something and would like the community's assistance.
Here is the partial settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ALLOWED_HOSTS = ['tryml.herokuapp.com','localhost']
# Application definition
INSTALLED_APPS = [
'web.apps.WebConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'tryml.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 = 'tryml.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.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/2.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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Here is the wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tryml.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Here is the html file trying to access the static content:
{% extends "web/base.html" %}
{% load static %}
{% block content %}
<div>
<img src="{% static 'web/img/target.jpg' %}" alt="Image could not be loaded"></img>
</div>
{% endblock %}
Here is the project structure:
tryml
--static
--web
--img
--target.jpg
--tryml
--settings.py
--wsgi.py
--urls.py
--web(web app)
--(urls,forms,templates,...)
--manage.py
--Procfile
--requirements.txt
--runtime.txt
One more observation, when I check the requests sent from my browser, it shows a 404 error for the static file(image) and says it tried to lookup here- ...herokuapp.com/static/web/img/target.jpg
Shouldn't it refer from STATIC_ROOT(staticfiles/web/img/target)?
EDIT-- The collectstatic command runs when the code is pushed on heroku,and it shows a successful copy step into app/staticfiles. Still, static file is not loading.
EDIT2--I ran the command python manage.py findstatic web/img/target.jpg as mentioned here: https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#findstatic
It returned the file location on local machine but on heroku, it says 'No matching file found for 'web/img/target.jpg'.' Why is it not being located even after a collectstatic command has run successfully?
How does the production fetch of static files actually work? When I use {% static web/img/target.jpg %}, does it go to the STATIC_ROOT location to fetch it?
You have to serve the static file using nginx or you have to add path in urls py.
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
After doing 'find' on the remote heroku server from my machine, I came to know that the file is stored as 'target.JPG' and not 'target.jpg'.
I changed the access link accordingly in the template and it worked.
On the local machine, the CAPS do not seem to matter as I had already played around with them earlier.
Also, my git push to heroku never really changed the filename to 'target.jpg' because it doesn't consider changes in the caps of the filename unless told to as mentioned here - Changing capitalization of filenames in Git
Thank You.

Django 2.0 reusable apps - TemplateDoesNotExist at /polls/

Python 3, Django 2.0
I just got to the end of the official Django tutorial, and I'm working on the advanced portion - "How to write reusable apps"
It seems like I was at least partially successful, I can access the Questions and Choices through the admin interface, but when I try to display the http://127.0.0.1:8000/polls/ I get this error: TemplateDoesNotExist at /polls/1/
I get a similar error for trying to access a detail page, at http://127.0.0.1:8000/polls/1/
I looked through all the troubleshooting questions I could, and my main question is - how can you access templates that are packaged into an app? The thing I see going wrong is that Django is trying to find the app templates inside the main project directories(ie: /tutorial/templates/polls/detail.html), but they should be "inside" the module I imported from pip.
Are you actually supposed to package the templates into apps this way? I tried throwing the template files back into tutorial/templates/polls/ and it works just fine, but this goes against what I think should be "reuseability" because then the packaged app won't have it's own templates.
The answers I was able to find seem to be more for older versions of Django, and used a TEMPLATE_LOADERS setting... Anyone know if there is a way to set that in Django 2?
Directory structure:
django-polls/
LICENSE
manifest.in
README.rst
setup.py
/dist
/docs
/polls
admin.py
apps.pyo
__init__.py
models.py
tests.py
urls.py
views.py
/build
/migrations
/static
/polls
/images
style.css
/templates
/polls
detail.html
index.html
results.html
The project structure is like this:
tutorial/
/mysite (settings.py, etc)
/templates
/admin
base_site.html
index.html
/venv (my virtualenv directory)
db.sqlite3
manage.py
settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*e7#6=f$r(cu_p#7#*s+6t9r^ouio$x&06s61-0u(n1mo370c6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# 'polls.apps.PollsConfig',
'polls',
'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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(BASE_DIR, 'templates', 'polls')],
'DIRS': [os.path.join(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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.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/2.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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
The issue here was case: the file had been named manifest.in, when it needed to be capitalized as MANIFEST.in. Happy holidays!
Remember to include your templates directory in your MANIFEST.in file. See step 6 of packaging your app for more info.