Setting DEBUG = False causes 500 Error
Asked Answered
R

34

329

Once I change the DEBUG = False, my site will generate 500 (using wsgi & manage.py 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

www.beta800.net:80 222.247.56.11 - - [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"
www.beta800.net:80 222.247.56.11 - - [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"
www.beta800.net:80 222.247.56.11 - - [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 
#TEMPLATE_DEBUG = DEBUG

HERE = os.path.dirname(__file__)
ADMINS = (
    ('admin', '[email protected]'),
)

MANAGERS = ADMINS

DATABASES = {
    '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:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# 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:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# 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/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# 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/media.lawrence.com/static/"
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')

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

# Additional locations of static files
STATICFILES_DIRS = (
    # 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.
    '/home/zdm/static',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    '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.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # 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'

TEMPLATE_DIRS = (
    # 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.
    '/home/zdm/templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'zdm',
    'portal',
    'admin',
    'tagging',
)
Resolute answered 28/2, 2013 at 5:27 Comment(7)
Yes, i have add 403 & 404 500 html file in my templates dirResolute
Do you have 500.html and 404.html and 403.html files in place? I think I recall having an issue with a deployed project that did not have those files in the root of my templates directory.Qualify
If your site is generating a 500 error there should be some info in the apache log, you might want to past a chunk of the end of the error log file for people to look at.Qualify
how did you handle or call the error? 500 will generate if you change your debug because the system didn't detect existing 404 templatesUnskillful
add some access log in my question. thanksResolute
You might want to change your SECRET_KEY now that it's publicly available...Kos
This isn't the answer for everyone. As shown below in https://mcmap.net/q/98486/-setting-debug-false-causes-500-error, there could be many reasons why this is occurring. With some simple logging you can find out without guesswork.Boraginaceous
J
426

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 https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

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

Jeffiejeffrey answered 28/2, 2013 at 5:43 Comment(13)
Wow - this bit us hard. It really sucks that this setting is buried in the docs. Our production site wouldn't work with DEBUG = False. Thank you for pointing this out!!!Tribalism
More on the security issues that introduced this setting: Practical HTTP Host header attacks. Will definitely convince you not to use ['*'] in production.Windjammer
bl. annoying that they don't even stick it in as a default value in settings.py, perhaps with an expanatory comment...Asir
If your settings file comes from a django 1.5 installation, the configuration ALLOWED_HOSTS will be there, with an explanatory comment (like what @Asir wanted). If you add your own entry of ALLOWED_HOSTS (and have an existing , duplicated ALLOWED_HOSTS ) you will continue to get 500 error .Director
Sometimes I wonder why Django is becoming more and more frustrating to work with! Surelly those guys are much better programmers than me, but I really don't understand the decision to "fix" vulnerabilities at the application level, when the real and clean move would be to configure the server properly. Same goes for "template caching" and "persistent connections" ... Useless code that will never be used in a serious website; still is presented as the holy grail of programming! Maybe is just me, I've been wrong before!Flareup
So another funny thing is that it matters where in the settings file you define ALLOWED_HOSTS. Put it in the beginning - the error persisted. Moved to the end of the file - worked!Allare
This solved my problem. This Blog post shows a detailed description of the error and solution. I had my server IP which I entered in the ALLOWED_HOSTS list to get rid of 500 error.Kantos
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 itGratuity
I set ALLOWED_HOSTS to ['*'] for testing purposes and still got a 500 after rebooting the server. No sign of trouble in the server log, only that damned HTTP 500. How do I obtain more error information without relying on DEBUG = True?Grandniece
Nevermind, found the problem. It was related to django-pipeline's behavior when the static hasn't been collected yet. As a general tip, placing a breakpoint in Django's handle_uncaught_exception method will help you figure out what's going on here.Grandniece
Why is this marked the correct answer? An incorrect ALLOWED_HOSTS gives a server 400 error, not a server 500.Reinwald
@Grandniece how did you fix your issue? I had the exact same problem. When I remove the static reference, I don't get the error anymoreInheritrix
I don't recall, I'd need a time machine to ask myself... The breakpoint in Django's handle_uncaught_exception method still sounds like a useful trick though!Grandniece
L
85

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:

# settings.py
LOGGING = {
    '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': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}
Lubricous answered 13/5, 2016 at 20:2 Comment(11)
This should be the accepted answer. It's much more useful to simply ask the framework itself what is wrong after using the production settings, instead of trying to guess.Porridge
Indeed, this is not something to wander around in the dark about. Just look at the error message you would normally see using this method. In my case, I was missing a different setting in my settings.py that my app was looking for. All I needed was the log to track this down. One important note: I added /path/to/my/django/ before the 'mysite.log' as shown in the docs example: docs.djangoproject.com/en/1.10/topics/logging/#examplesBoraginaceous
I have spent hours looking for a solution, no use. according to this answer just use logging and you should have your problem, this is the best answer. Thanks OP!Maverick
My server errors do not seem to produce any logs! I have tried various logging configs to no avail. Any ideas?Accommodation
Thank you! This solved my error. Turns out I needed to run collectstatic to collect some static assets from a package.Bicipital
I added this to my settings and it tells me it wont run because of not having permission to access the log. I gave the permissions I even changed ownership of the log to root. I commented out this logging script but nothing. PermissionError: [Errno 13] Permission denied: '/mysite.log' ValueError: Unable to configure handler 'file'Sumac
@Sumac There could be a number of reasons why you get permission denied, Start with is the python application running as the user your expecting | ./mysite.log is a relative path is your PWD where you think it is. Is there some security blocking it such as SELINUXLubricous
@Lubricous I tried figuring it out but nothing. Since I am developing I had the luxury of just loading a previous version and moved on. I gave permission to everything, erased the code. Tried to clear the tracks so to speak but it kept asking for access to that logfile which I touched and gave permissions just in case. It was a weird one, I could not say for sure.Sumac
@Sumac if you have a sys admin in your team holla at them. They are best at troubleshooting permission denied. Like I say there's a lot of things that can get in the way.Lubricous
Where does mysite.log get placed? It's not in the root directory of my project on Heroku using heroku run ls.Oxytetracycline
This is the real solution!!! Thanks a lot mateEnchantress
C
62

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: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions

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

Cease answered 10/2, 2018 at 19:16 Comment(4)
I go the same thing but collectstatic did not fix it for me. Did you get a "can't be reached error"? In that case, how did you fix it?Rasia
Why is this so far down? This helps no matter what the reason for the error is.Tui
This should be the answer to the question "How do I debug a 500 error in Django".Acetic
Note that according to the document linked in the answer, this shouldn't be enabled in production (without a complete understanding of what it does).Bullfrog
A
27

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

COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
Antagonistic answered 22/6, 2015 at 19:3 Comment(2)
Thanks that was the reason it didn't work for me, but doesn't that line disable django_compressor from doing its job?Advisement
@Advisement Nope. No harm is involved. django-compressor.readthedocs.io/en/latest/settings/… Compressor would still be doing its job perfectly! Simply compress all your statics (like css), so that setting is thus useless as your assets are already compressedAntagonistic
N
20

Its mid 2019 and I faced this error after a few years of developing with Django. Baffled me for an entire night! It wasn't allowed host (which should throw a 400), everything else checked out, finally did some error logging only to discover that some missing / or messed up static files manifest (after collectstatic) were screwing with the setup. Long story short, for those who are stumped AND SO HAPPEN ARE USING WHITENOISE OR THE DJANGO STATICFILE BACKEND WITH CACHE (manifest static files) , maybe this is for you.

  1. Make sure you setup everything (as I did for the whitenoise backend...django backends read on nonetheless) http://whitenoise.evans.io/en/stable/django.html

  2. If error code 500 still shoots you down, take note on your settings.STATICFILES_STORAGE.

Set it to either (for whitenoise backend with compression)

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

or (leave as django default)

STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage

All in all, THE PROBLEM seemed to come from the fact that this whitenoise cache + compression backend -->

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

or the django's own caching backend -->

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

...didnt quite work well for me, since my css was referencing some other sources which may be mixed up during collectstatic / backend caching. This issue is also potentially highlighted in http://whitenoise.evans.io/en/stable/django.html#storage-troubleshoot

Nigelniger answered 22/5, 2019 at 15:2 Comment(3)
Changing to this - whitenoise.storage.CompressedStaticFilesStorage - worked for me.Trudeau
While I still have some other things to figure out and fix, this seems like it was the answer for me. One of these days I will fully understand how static files work in production. I don't know why it confuses me so much.Unwary
THANK YOU! This was driving me crazy. This error only happens in a remote environment with DEBUG set to False.Anonym
F
13

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

ALLOWED_HOSTS = ['localhost']
Fletcherfletcherism answered 17/5, 2013 at 15:35 Comment(1)
For whatever reason, using 'localhost' didn't work for me. I had to use the IP '127.0.0.1' instead. I was also able to use '*' if you're freaking out and just want it to work. I wouldn't advise doing that in production, however. OSX running Django 1.4.20Analcite
A
13

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.

Averir answered 18/6, 2013 at 8:23 Comment(5)
just use reverse and url tag and you should be fineExhortative
setting DEBUG=False can unveil import errors as well: #25676953Schoolman
even links to js and css assets?Gratuity
@amchugh89: no, just "django" URLsAverir
My issue is that whitenoise wasn't able to find some image and was throwing ValueError. I also couldn't find it, but didn't know how to tell whitenoise not to look for it. So I turned whitenoise off, use the django static serve and now I can run debug=False in prod. Obviously not ideal :(Gratuity
R
9

Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in settings.py 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 = [".your_domain_name.com",]
    ...
else:
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
    ...

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", "127.0.0.1",]
else:
    ...
Raggedy answered 6/5, 2016 at 23:44 Comment(0)
C
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.

Cruikshank answered 5/1, 2014 at 18:36 Comment(3)
This was my issue also, the base template that the custom 404 page was referencing used the static tag but did not include the {% load static %} at the top. I didn't notice it elsewhere because my other templates had this line but makes sense to put it in the base anyhow as it refers to static files all over the place.Mercaptide
Same solution here - I was using static to include a CSS file that didn't exist.Kossuth
this was the most hilarious problem I have ever had. Quizzed me for 2 hours straight.Haemin
I
8

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

python manage.py collectstatic

in settings.py, the code should look something like this:

STATIC_URL = '/static/'

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

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Itis answered 30/4, 2017 at 0:59 Comment(0)
I
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 setting.py 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 settings.py, which lacked what hwjp requested--- a "default value in settings.py, 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 settings.py 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.

Injun answered 9/10, 2013 at 9:55 Comment(3)
i had exactly the same hilarious pattern !, except that it became hilarious only after I found this, thanks. before that it was just plain frustratingDirector
Something that helps in all this is to use a local_settings.py for each environment and then import it in settings.py.Carmancarmarthen
what i like to do, is have a settings/ directory instead of a settings.py. In this directory, you can have separate .py files for different environments, and a base.py for general settings. Production dependant settings can then start by importing * from the base settings, and just override whatever they need to override. Also, the required init.py needed to turn that settings/ directory into a valid module, can first import from base.py, and then try to import from a local.py (which would only exist locally). that would mean you don't need to specify local settings manuallyDocila
G
7

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

EDIT

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

Gratuity answered 23/11, 2015 at 18:17 Comment(3)
I had the same problem with whitenoise. python manage.py collectstatic fixed it.Blotchy
@amchungh89 you are a life saver! Thanx for pointing that out.Loosen
handler404 also fixed my problem.Was
E
6

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 manage.py runserver in the command line to see any errors that wont appear in any web error logs.

Eupatrid answered 24/6, 2016 at 20:28 Comment(0)
K
5

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 settings.py 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 = ['www.example.com'] # 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 = ['123.123.198.123'] # Enter your IP here

3: If you are testing on local server, you can edit your settings.py or settings_local.py as:

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

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.

Kantos answered 2/2, 2015 at 6:58 Comment(0)
B
3

I know this post is quite old but it's still perfectly relevant today.

For what it's worth - I was getting a 500 with DEBUG = False for all pages on my site.

I got no traceback when in debug.

I had to go through every static link in my templates within my site and found one / (forward slash) in front of my image source. {% static ... %}. This caused the 500 error in DEBUG = False but worked perfectly fine in Debug = True with no errors. Very annoying! Be warned! Many hours of time wasted due to a forward slash...

Berget answered 30/4, 2020 at 15:6 Comment(1)
Wow! thanks for saving time. I had a static tag pointing to non existing file and was throwing 500 on Debug=False.Asthmatic
C
3

You might want to run python manage.py collectstatic after you set DEBUG = False and ALLOWED_HOSTS = ['127.0.0.1'] in settings.py. After these two steps my web application ran well in my local server even with DEBUG=False mode.

BTW I have these settings in settings.py.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware', # what i added
    'django.middleware.common.CommonMiddleware', # and so on...
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

I assume maybe whitenoise setting has something to do with collectstatic command.

Catania answered 20/5, 2020 at 5:25 Comment(0)
I
2

I have the similar issue, in my case it was caused by having a Commented script inside the body tag.

<!--<script>  </script>-->
Itis answered 18/4, 2017 at 19:19 Comment(0)
Y
1

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 myproject.ca www.myproject.ca;
    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;
}
Yokoyokohama answered 10/10, 2013 at 18:6 Comment(2)
my gunicorn config file is as follows: #!/bin/bash cd /var/web/delicms_env/deli_cms/ source ../bin/activate exec gunicorn --workers=3 deli_cms.wsgi:applicationYokoyokohama
my problem is now solved, I was using the gunicorn_django script and it was giving me deprecated messages. Still not sure why it worked locally, didn't change my nginx config just changed the old script to use gunicorn and use the wsgi:application module instead and it works again. Gunicorn was throwing some deprecation messages before this as well but nothing specific to my issue.Yokoyokohama
C
1

A bit late to the party, and off course there could be a legion of issues but I've had a similar issue and it turned out that I had {% %} special characters inside my html remark...

<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->
Cafeteria answered 29/10, 2016 at 10:22 Comment(0)
S
1

I ran into this issue. Turns out I was including in the template, using the static template tag, a file that did not exist anymore. A look in the logs showed me the problem.

I guess this is just one of many possible reasons for this kind of error.

Moral of the story: always log errors and always check logs.

Subtenant answered 18/9, 2017 at 10:39 Comment(0)
V
1

Thanks to @squarebear, in the log file, I found the error: ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>.

I had a few problems in my django app. I removed the line
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' which I found from the heroku's documentation.

I also had to add extra directory (thanks to another SO answer) static in the root of django application as myapp/static even though I wasn't using it. Then running the command python manage.py collectstatic before running the server solved the problem. Finally, it started working fine.

Vocation answered 26/12, 2017 at 13:56 Comment(1)
How does this answer the original question?Franciscafranciscan
C
1

this maybe help someone else, in my case the problem with the missing favicon.

Comitative answered 15/2, 2020 at 0:35 Comment(0)
H
0

I know this is an old question, but I was also getting a 500 error when DEBUG=False. After several hours, I realized I had forgot to end some of the links in my base.html with a trailing slash.

Hospitalization answered 10/1, 2015 at 1:35 Comment(1)
even the css and js stuff?Gratuity
B
0

This is old and my problem ended up being related to the problem but not for the OP but my solution is for anyone else who tried the above to no avail.

I had a setting in a modified version of Django to minify CSS and JS files that only ran when DEBUG was off. My server did not have the CSS minifier installed and threw the error. If you are using Django-Mako-Plus, this might be your issue.

Beetlebrowed answered 7/10, 2015 at 20:53 Comment(0)
M
0

One small thing to note, If the array has None in it, then all the subsequent allowed hosts are ignored.

ALLOWED_HOSTS = [
    "localhost",
    None,
    'example.com', # First DNS alias (set up in the app)
    #'www.example.com', # Second DNS alias (set up in the app)
]

Django version 1.8.4

Morphinism answered 1/3, 2016 at 15:5 Comment(0)
U
0

I had one view that threw a 500 error in debug=false but worked in debug=true. For anyone who is getting this kind of thing and Allowed Hosts is not the problem, I fixed my view by updating a template's static tag that was pointing to the wrong location.

So I'd suggest just checking links and tags are airtight in any templates used, maybe certain things slip through the net in debug but give errors in production.

Ultun answered 2/5, 2017 at 12:23 Comment(0)
C
0

I found yet another cause of the 500 error when DEBUG=False. I use the Django compressor utility and our front-end engineer added references to font files inside a compress css block in a Django template. Like this:

{% compress css %}
    <link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
    <link href="{% static "css/bootstrap-spinedit.css" %}" rel="stylesheet">
    <link href="{% static "djangular/css/styles.css" %}" rel="stylesheet">
    <link href="{% static "fonts/fontawesome-webfont.ttf" %}" rel="stylesheet">
{% endcompress %}

The solution was to move the link to the ttf file below the endcompress line.

Corncob answered 10/10, 2017 at 20:39 Comment(0)
G
0

I had a problem similar to this and I will report how I solved mine because it could be that someone is also experiencing the same.

In my case, the error was caused because the server was not finding some static files from the homepage.

So make sure the error only occurs in the index or occurs on another page. If the problem is only occurring in the index very probably you need to check the static files. I recommend opening the Chrome preview console and checking for any errors.

In my case, the server couldn't find favicon.ico and two other CSS.

To fix this I passed python manage.py collectstatic and it worked.

Groomsman answered 18/7, 2019 at 22:10 Comment(0)
S
0

I started to get the 500 for debug=False in the form of

django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.

when raising django.core.exceptions.ValidationError instead of raising rest_framework.serializers.ValidationError

To be fair, it was already raising a 500 before, but as a ValidationError, with debug=False, this changed into the NoReverseMatch.

Skijoring answered 27/8, 2019 at 20:30 Comment(0)
C
0

I had this issue and solved it by removing this line: STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage

Copyreader answered 9/10, 2023 at 11:11 Comment(0)
B
0

For posterity, using logs in Django to find causes of Internal Server Error.

Once DEBUG=False, Django will no longer log debug messages for you. Setup logs before you launch your server into production!

import os

LOG_FILE = os.path.join(BASE_DIR, "server.log")

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "file": {
            "level": "DEBUG",
            "class": "logging.FileHandler",
            "filename": LOG_FILE,
        },
    },
    "loggers": {
        "django": {
            "handlers": ["file"],
            "level": "DEBUG",
            "propagate": True,
        },
    },
}

Now when you encounter an Internal Server Error, you can simply check your server.log to know what is going on.

Banana answered 5/4 at 7:26 Comment(0)
B
-1

my problem was in wrong 404.html template - I copy&pasted

<a href="{% url 'home:index' %}">

instead of (in my case)

 <a href="{% url 'posts:index' %}">

that's why 500 apperar

Belloc answered 23/1, 2022 at 20:56 Comment(0)
M
-5

Ok after trying soo many things, the correct solution is ...

you need to set DEBUG = 'FALSE' not False or FALSE, but 'FALSE' with ''

Minimalist answered 21/3, 2020 at 16:18 Comment(1)
I think 'FALSE' is a string, so it's equal to True, that's why it does not get an error.Stepsister
F
-7

If you want to allow for all hosts. Use ALLOWED_HOSTS = ['*',] instead of ALLOWED_HOSTS = ['*']

Funnel answered 17/12, 2013 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.