Hitting 500 error on django with debug=False even with ALLOWED_HOSTS=["*"]

Question:

I am getting 500 errors on every page I try to go with. The only thing that i’m changing is DEBUG to False.

Here is my config:

SECRET_KEY = os.environ.get("SECRET_KEY", "0$ke!x1bz5cj0mpzo1zfx4omw-c9iqw%m95zb)(2@ddg5s+3!f")

ALLOWED_HOSTS = ['*']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False


# Application definition

INSTALLED_APPS = [
    'posts', # Contains all dynamic and static pages related to posts
    'courses', # Contains all dynamic and static pages related to courses and modules
    'pages', # Contains all static pages that are not post related
    'markdownx', # Allows for editing and creating markdown content
    'jet.dashboard',
    'jet', # Django admin theme override
    'pwa', # Sets app to be PWA compliant
    'whitenoise.runserver_nostatic', # Serving static files
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Literally every answer i’ve seen says just set your ALLOWED_HOSTS to [‘*’], as you can see i’ve done that and still no dice. I checked the Docs and they are pretty sparse on what else DEBUG mode effects there is a section of the docs that says:

As a security measure, Django will not include settings that might be sensitive, such as SECRET_KEY. Specifically, it will exclude any setting whose name includes any of the following:
‘API’
‘KEY’
‘PASS’
‘SECRET’
‘SIGNATURE’
‘TOKEN’

https://docs.djangoproject.com/en/2.2/ref/settings/#debug

The only thing I can think of is that the secret_key is not being picked up, but if so how do you do this in production?

EDIT: Some people have been asking me to turn debug mode to true to get the traceback. The problem is, when I set it to true I don’t get the 500 error, it’s only when DEBUG = False.

Asked By: Kieran Wood

||

Answers:

So, the issue was related to a SINGLE ICON NOT LOADING, the path was off but due to the way Django handles static files (which is honestly dumb) when DEBUG=True I didn’t catch it, and when DEBUG=False there was no traceback.

A neat trick I learned was you can force Django to give you the logging information you need by attaching an explicit logger in your main settings.py like so:

import logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
    },
}

So three things I learned in my 6 hours of debugging you are in my situation:

  1. Set DEBUG = False right away in your development cycle, it will force you to configure collectstatic properly.
  2. Heroku’s documentation for getting your app setup lies about how to configure WhiteNoise properly, so here is the real configuration:
STATIC_URL = '/static/'

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

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

STATICFILES_STORAGE = '.storage.WhiteNoiseStaticFilesStorage' # Read point 3 for details about this
  1. You have to subclass WhiteNoises default configuration locally to remove Djangos built in manifest_strict attribute (got that from here: https://stackoverflow.com/a/51580328/11602400)
from whitenoise.storage import CompressedManifestStaticFilesStorage


class WhiteNoiseStaticFilesStorage(CompressedManifestStaticFilesStorage):
    manifest_strict = False
Answered By: Kieran Wood

Adding an answer since this just took me a couple hours to debug and this will maybe save someone else from the same problem.

I was only getting SERVER ERROR 500 on certain admin pages. Some models would work fine, others didn’t. I suspected a third-party module at that point.

This problem showed up for me because I am using django-nested-inline and there was a bug in the version installed via pip that couldn’t locate a copy of jQuery that is necessary to modify the admin pages to handle the nested inlines.

This bug was fixed so I needed to remove the version I was using and then install the fixed version directly from Github.

Answered By: pspahn

I solved mine by

  1. Put DEBUG=True in the project/settings.py

  2. Run

$ python manage.py collectstatic

Any error in your static files will appear in your terminal if there is any. Try solving that error before you proceed.

  1. Go into your main project/settings.py
    And instead of making a generally allowed host by using "*".
    Replace it with your localhost link
    Eg: 127.0.0.1.

  2. Go into your browser’s history and delete recent cookies and cache.

  3. Refresh your projects and that’s all.

Answered By: Coding Rev

Adding an answer because this stumped me for a while and a lot of answers, whilst they do apply to collect your static files the server error 500 can also occur if you have any files/images/CSS/js reference in HTML that isn’t actually present in your project directory. For example if you reference <link href="{% static 'app/css/newStyle.css' %}" rel="stylesheet" /> and that file does not exist then you’ll get this error.
Best way to check which files aren’t actually present is to run in your local environment python manage.py runserver and load pages, to see where there is a 404 error in the terminal,

It will probably look like this:
"GET /static/app/css/newStyle.css HTTP/1.1" 404 1876
Then you can omit the reference to this file if not needed or locate where to add it in.

Answered By: Arcade
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.