Django returning 500 Internal Server Error instead of index.html when Debug = False

Question:

I have a problem in my django web application in which django returns a 500 error when trying to get the index.html file. This only happens when Debug = False and it only happens with this one template. All the other templates render normally without errors.

I have already tried the whitenoise settings, favicon.ico errors, checked all routes and everything seems to be fine, I really can’t find the error. The weird thing is that it is only happening in index.html.

If someone can help I will really appreciate it, thanks in advance.

settings.py

DEBUG = False
ALLOWED_HOSTS = ['vilytic.herokuapp.com', '127.0.0.1']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'accounts',
    'comparer',
]

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'video_search': '8/day',
        'video_id': '8/day'
    }
}

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',
]

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',
            ],
        },
    },
]

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Error that appears in terminal

"GET / HTTP/1.1" 500 145

urls.py

from django.contrib import admin
from django.urls import path, include
from . import views
from django.views.generic.base import RedirectView
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name="index"),
    path('accounts/', include('accounts.urls'), name="accounts"),
    path('comparer/', include('comparer.urls'), name="comparer"),
    path('contact/', views.contact, name="contact"),
    path(
        "favicon.ico",
        RedirectView.as_view(url=staticfiles_storage.url("favicon.ico")),
    ),
]

views.py

from django.shortcuts import render
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.conf import settings


def index(request):
    return render(request, 'index.html')
Asked By: Diegoa87

||

Answers:

It means that you have an error and because DEBUG = FALSE it doesn’t show the error. You can see the error in the console or by enabling DEBUG

Answered By: D4NieLDev

I’ve encountered this before with Whitenoise, it’s tricky to find the cause. Assuming of course that you have no errors when DEBUG = True, try setting

WHITENOISE_AUTOREFRESH = True

in your settings.py.

Answered By: John Kealy

It turns out that a png file was causing the problem. I don’t know why png files sometimes get saved with capital letters, like PNG. Apparently that was causing a problem with whitenoise. It took me a long time to figure it out, hope it helps.

Answered By: Diegoa87

Mine gave a similar error trying to get the index file.

The error happend because my urls were configured this way:

path('admin/', admin.site.urls)

and trying to get http://127.0.0.1:8000/admin WITHOUT the /.

Either you can remove the / from the path or get http://127.0.0.1:8000/admin/.

Answered By: Rita Alamino

For me, there was an issue with static template-tag but white-nose did provide me any useful information about issue/error.

There was error in the address of a static file:

<link rel="icon" href="{% static 'images/favicon.png' %}">

was supposed to be

<link rel="icon" href="{% static 'blog/images/favicon.png' %}">

After correcting the address it fixed my issue.

Answered By: Abdullah

Solution

I had this issue recently and I had to remove

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

and replace it with

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

I hope this helps.

have a nice day

Answered By: Anthony Aniobi

You can change STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' to STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'.

You will keep the compression while serving files, but you’ll loose the hashing of the static files filenames.

What does this "hashing" of filenames even mean?

What whitenoise.storage.CompressedManifestStaticFilesStorage does is save the static files during the collectstatic method as an additional file with an unique hashed name into your STATIC_ROOT directory.

When you use whitenoise to serve your static files, it caches the files with a default Cache-Control of 4 hours in the browser. This means that the visitors of your page, when they first visit your site, get the static files, and if they visit again inside of this 4 hour window, they will use the cached version of the static files. This results in faster page loading times.

You could set this cache control to a longer time (like 1 year), this however means that any update you do to your static files, will not be visible to the users if they still got the cached version of the static files in their browsers.

Django offers a way around this with ManifestStaticFilesStorage. It saves the files with a hash generated filename which only changes if the file is updated. Whitenoise treats these files as new files and updates them in the browser cache if they are changed. You basically get the best of two worlds: longer Cache-Control and the users browser gets the new files if they are changed.

For some reason, django isn’t reading your hashed filenames. This has little to do with whitenoise, and is a django "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" problem. Try to get it working without whitenoise first and figure out why "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" throws the 500 server error.

I personally had the same problem and couldn’t find a solution anywhere. I decided to keep the compression and leave the shelf life of the static files at the default 4 hours.

Answered By: cosmic89