Not able to refer static files of Django project from Heroku - django

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.

Related

Not able to load images from static folder in django

Not able to load image from static dir in Django. Below is the picture of my file structure.
In settings.py S
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
When I try to load the image file from STATIC_URL, it is producing this error:
it is just not loading images but the text from my home-view.html is loading file thus django is not able to locate the image files. Could you please advise why are images not loading?
home-view.html
{% load static %}
<html>
<head>
{{time}}
<img src="{% static 'myproject/images/test.png' %}" alt="My image">
</head>
</html>
My complete settings.py file :
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/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
print("Path is : ", os.path.join(BASE_DIR, 'myproject/template'))
# 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-(ep(j)h+$(zro2!9r3bm0fj^!84-1c9d+)$be4hgrq4_#6d^r-'
# 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',
'myproject'
]
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 = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'myproject/template')],
'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 = 'myproject.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_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
]
print("static path" , STATICFILES_DIR)
print(STATIC_URL)
# print("static file : ", (os.path.join(BASE_DIR, '/static')), )
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
instead of this:
STATICFILES_DIR = [os.path.join(BASE_DIR,'static'),]
Do this and try:
STATICFILES_DIRS = [os.path.join(BASE_DIR,'appname/static'),]
and also add this:
os.path.join(BASE_DIR, 'appname', 'templates')
{% load static %}
<html>
<head>
{{time}}
<img src="{% static '/myproject/images/test.png' %}" alt="My image">
</head>
</html>
and make sure you create folder called templates instead of template
I hope this may be help you

TemplateDoesNotExist at / index.html error when django+react app deployed to Heroku

I created a simple django & react app (which just loads react default page for now) and I am trying to deploy to Heroku. When I run python manage.py runserver on localhost it runs fine (with default react page showing), but when I deploy it to Heroku, I get the following error:
TemplateDoesNotExist at /
index.html
This is the site : https://temp-app-test.herokuapp.com/
I'm pretty sure I included index.html in templates using os.path.join(BASE_DIR, 'build') in settings.py, but it doesn't work. I also included "postinstall": "npm run build" in scripts in package.json file.
requirements.txt
asgiref==3.2.7
Django==3.0.6
pytz==2020.1
sqlparse==0.3.1
whitenoise==5.0.1
gunicorn==20.0.4
runtime.txt
python-3.7.4
Procfile
release: python manage.py migrate
web: gunicorn test_test_test.wsgi --log-file -
settings.py
"""
Django settings for test_test_test project.
Generated by 'django-admin startproject' using Django 2.2.10.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret'
# 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',
]
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 = 'test_test_test.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'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 = 'test_test_test.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.2/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.2/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.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
urls.py
from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^.*', TemplateView.as_view(template_name='index.html'),
]
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_test_test.settings')
application = get_wsgi_application()
I've been stuck here for hours, and I would like some help on this! Thanks in advance.

How to deploy static files in Django before hosting it anywhere?

I have a Django application which needs to be deployed. Currently, I am not using Heroku or a Linux server to deploy it. However, I am trying to follow along with the Django checklist and ensure whether if it's ready to be deployed.
I had done the following in my settings.py module:
Set DEBUG = False
Allowed_Hosts = ['*']
STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles")
This is my settings.py module:
"""
DJANGO PROJECT
"""
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'SECRET KEY STORED IN ENVIRON VARIABLE'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'main.apps.MainConfig', #placing the Django app here.
'crispy_forms',
'rest_framework',
'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 = 'main.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 = 'main.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_db', #name of the database.
'USER' : '######',
'PASSWORD' : '######',
'HOST' : 'localhost',
'PORT' : '',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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.2/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.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CRISPY_TEMPLATE_PACK = 'bootstrap4'
After this, I typed the following command below:
python manage.py collectstatic
Now, when I run the server, my web app broke and none of the static files i.e CSS, media and JS are used. It's just plain HTML stuff.
The weird part is that, when I changed the DEBUG mode to True, the site works normally.
Can anyone explain the reason for this? How can I deploy a site when the DEBUG mode is set to True?
Because you have this settings in your main urls
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If you want to deploy the application in cloud server, there you have to create one static folder outside your main folder and place your static files there, so the collectstatic command will store your static files there.

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 Heroku Server Error page 500 only when Debug = False , When Debug on True everything works fine. Why?

My Djangoproject call: myDebug
and my Django app call: Deb
it is on Heroku: meindebug.herokuapp.com
settings.py
import os
import django_heroku
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = False
ALLOWED_HOSTS = ['meindebug.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Deb',
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'myDebug.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 = 'myDebug.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
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.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
django_heroku.settings(locals())
!!! please notice i tried it with ALLOWED_HOSTS = ['*'] but nothing changed !!!
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myDebug.settings")
application = get_wsgi_application()
application = WhiteNoise(application, root='/static/Deb/Images/')
application.add_files('/static/Deb/Images/', prefix='more-files/')
Procfile
web: gunicorn myDebug.wsgi
Pipfile
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
gunicorn = "*"
django-heroku = "*"
whitenoise = "*"
[dev-packages]
[requires]
python_version = "3.6"
Since two Weeks i tried to fix that issue.
Unfortunately, I was not successful.
Nowhere i find a real Fix. Only some words there and there but noone have a real Solution.
First you have to run python manage.py collectstatic.
Then in Heroku the Config Variables to COLLECTSTATIC = 1.
but the file Path to your Pictures/Files have to show like this
{% static "MyApp/Images/Picture.png" %}
you get an Error if you write it so
{% static "/MyApp/Images/Picture.png" %}
the slash at front of MyApp is the problem. So write it without slash then it works.
If you have a favicon in the head then you have to write it so
<link rel="shortcut icon" href="https://www.yourwebsite.de/static/MyApp/Images/favicon.ico">
For what it's worth, you'll face the same issue if you have an html comment in your code that calls the template tag "static" (probably the behavior is the same for every commented template tag), this was my case:
<!-- <img src="{% static 'main_website/images/image.jpg' %}" alt=""> -->
removing the comment resoled the 500 error (which also, was not being logged).
I had a same issue it appears that I had some css file linked but the original files were deleted. please make sure you aren't linking any not existing external file.