Setting DEBUG = False causes 500 Error

Setting DEBUG = False causes 500 Error

Once I change the DEBUG = False, my site will generate 500 (using wsgi & runserver), and there is no error info in Apache error log and it will run normally when I change debug to True .
I'm using Django 1.5 & Python 2.7.3
here is Apache access log and without any log in apache error log - - [28/Feb/2013:13:42:28 +0800] "GET / HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22" - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22" - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"

Here is my settings file:
import os.path    
DEBUG = False 

HERE = os.path.dirname(__file__)
    ('admin', ''),


    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'zdm',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'passwd',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.

# Local time zone for this installation. Choices can be found here:
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:


# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/"

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "", ""

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/"
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')

# URL prefix for static files.
# Example: ""
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')
S= os.path.join(HERE, 'static').replace('\\','/')

# Additional locations of static files
    # 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.

# List of finder classes that know how to find static files in
# various locations.
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',

# Make this unique, and don't share it with anybody.
SECRET_KEY = '9a7!^gp8ojyk-^^d@*whuw!0rml+r+uaie4ur$(do9zz_6!hy0'

# List of callables that know how to import templates from various sources.
#     'django.template.loaders.eggs.Loader',

    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',

ROOT_URLCONF = 'zdm.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'zdm.wsgi.application'

    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.

    # Uncomment the next line to enable the admin:
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',


Answer 1:

Django 1.5 introduced the allowed hosts setting that is required for security reasons. A settings file created with Django 1.5 has this new section which you need to add:

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See

Add your host here like [''] or ['*'] for a quick test, but don’t use ['*'] for production.

Answer 2:

I know this is late but I ended up here with a search for my error 500 with DEBUG=False, in my case it did turn out to be the ALLOWED_HOSTS but I was using os.environ.get('variable') to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False:

    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        'simple': {
            'format': '%(levelname)s %(message)s'
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
    'loggers': {
        'django': {
            'propagate': True,
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',

Answer 3:

I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True. See here:

In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'. I fixed that by locally running python collectstatic.

Answer 4:

In my case, reading docs of third party apps properly saved me.

The culprit? django_compressor

I had

{% load compress %}
{% compress css %}
 ... css files linked here ..
{% endcompress %}

DEBUG = True always gave me 500. To fix it, I needed a line in my settings to get it running


Answer 5:

Right, in Django 1.5 if DEBUG = False, configure ALLOWED_HOSTS, adding domains without the port number. example:

ALLOWED_HOSTS = ['localhost']

Answer 6:

You must also check your URLs all over the place. When the DEBUG is set to False, all URLs without trailing / are treated as a bug, unlike when you have DEBUG = True, in which case Django will append / everywhere it is missing. So, in short, make sure all links end with a slash EVERYWHERE.

Answer 7:

I have a hilarious story for all. After reaching this page I said “Eureka! I’m saved. That MUST be my problem.” So I inserted the required ALLOWED_HOSTS list in and… nothing. Same old 500 error. And no, it wasn’t for lack of a 404.html file.

So for 2 days I busied myself with wild theories, such as that it had something to do with serving static files (understand that I am a noob and noobs don’t know what they’re doing).

So what was it? It is now Mr. Moderator that we come to a useful tip. Whereas my development Django is version 1.5.something, my production server version is 1.5.something+1… or maybe plus 2. Whatever. And so after I added the ALLOWED_HOSTS to the desktop version of, which lacked what hwjp requested— a “default value in, perhaps with an explanatory comment”— I did the same on the production server with the proper domain for it.

But I failed to notice that on the production server with the later version of Django there WAS a default value in with an explanatory comment. It was well below where I made my entry, out of sight on the monitor. And of course the list was empty. Hence my waste of time.

Answer 8:

For what it’s worth – I was getting a 500 with DEBUG = False on some pages only. Tracing back the exception with pdb revealed a missing asset (I suspect the {% static ... %} template tag was the culprit for the 500.

Answer 9:

Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in when switching between development and production.
I am using this code to set these setting automatically:

import socket

if socket.gethostname() == "server_name":
    DEBUG = False
    ALLOWED_HOSTS = ["",]
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "",]

If you use macOS you could write a more generic code:

if socket.gethostname().endswith(".local"): # True in your local computer
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "",]

Answer 10:

I faced the same problem when I did DEBUG = FALSE. Here is a consolidated solution as scattered in answers above and other posts.

By default, in we have ALLOWED_HOSTS = [] . Here are possible changes you will have to make in ALLOWED_HOSTS value as per scenario to get rid of the error:

1: Your domain name:

ALLOWED_HOSTS = [''] # Your domain name here

2: Your deployed server IP if you don’t have domain name yet (which was my case and worked like a charm):

ALLOWED_HOSTS = [''] # Enter your IP here

3: If you are testing on local server, you can edit your or as:

ALLOWED_HOSTS = ['localhost', '']

4: You can also provide ‘*’ in the ALLOWED_HOSTS value but its not recommended in the production environment due to security reasons:

ALLOWED_HOSTS = ['*'] # Not recommended in production environment

I have also posted a detailed solution on my blog which you may want to refer.

Answer 11:

ALLOWED_HOSTS is NOT the only issue, for me I had to make a 404.html and put it in the base level of my templates (not app level) – Also, you can make a 404 view and add a 404handler url but I think thats optional. 404.html fixed it

in mainproject.urls

handler404 = 'app.views.custom_404'

in app.views

def custom_404(request):
    return render(request, '404.html', {}, status=404)

then make a templates/404.html template

got this from another S/O post that I cannot find it


also, I get 500 errors when I serve assets with whitenoise. Could not figure that out for the life of me, error was ValueError from whitenoise not being able to find an asset that I also could not find, had to go with default django serving for now

Answer 12:

I was searching and testing more about this issue and I realized that static files directories specified in can be a cause of this, so fist, we need to run this command

python collectstatic

in, the code should look something like this:

STATIC_URL = '/static/'

    os.path.join(BASE_DIR, 'static'),

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

Answer 13:

I know that this is a super old question, but maybe I could help some one else. If you are having a 500 error after setting DEBUG=False, you can always run the runserver in the command line to see any errors that wont appear in any web error logs.

Answer 14:

I think it could also be the http server settings. Mine is still broken and had ALLOWED_HOSTS the entire time. I can access it locally (i use gunicorn), but not via the domain name when DEBUG=False. when I try using the domain name it then gives me the error, so makes me think its a nginx related issue.

Here is my conf file for nginx:

server {
    listen   80;
    server_name localhost;
    root /var/web/myproject/deli_cms;

    # serve directly - analogous for static/staticfiles
    location /media/ {
        # if asset versioning is used
        if ($query_string) {
            expires max;
    location /admin/media/ {
        # this changes depending on your python version
        root /var/web/myproject/lib/python2.6/site-packages/django/contrib;
    location /static/ {
    alias /var/web/myproject/deli_cms/static_root/;

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;
        proxy_pass http://localhost:8000/;
    # what to serve if upstream is not available or crashes
    error_page 500 502 503 504 /media/50x.html;