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.
82๐
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',
},
}
}
- [Django]-Django โ how to unit test a post request using request.FILES
- [Django]-Django models avoid duplicates
- [Django]-How to define two fields "unique" as couple
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
.
- [Django]-Django + Ajax
- [Django]-How can I upgrade specific packages using pip and a requirements file?
- [Django]-Django storages aws s3 delete file from model record
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)
- [Django]-Strings won't be translated in Django using format function available in Python 2.7
- [Django]-IOS app with Django
- [Django]-How to use regex in django query
19๐
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.
-
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
-
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
- [Django]-How does one make logging color in Django/Google App Engine?
- [Django]-Django Admin Form for Many to many relationship
- [Django]-What does error mean? : "Forbidden (Referer checking failed โ no Referer.):"
13๐
Right, in Django 1.5 if DEBUG = False
, configure ALLOWED_HOSTS, adding domains without the port number. example:
ALLOWED_HOSTS = ['localhost']
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-Django middleware difference between process_request and process_view
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.
- [Django]-How do Django models work?
- [Django]-Logging in Django and gunicorn
- [Django]-Django manage.py runserver invalid syntax
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:
...
- [Django]-Override existing Django Template Tags
- [Django]-How to save pillow image object to Django ImageField?
- [Django]-Http POST drops port in URL
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.
- [Django]-Django gunicorn sock file not created by wsgi
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?
- [Django]-Many-To-Many Fields View on Django Admin
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')
- [Django]-Django Rest Framework model serializer with out unique together validation
- [Django]-Altering one query parameter in a url (Django)
- [Django]-Serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
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.
- [Django]-How to combine django "prefetch_related" and "values" methods?
- [Django]-How do you change the collation type for a MySQL column?
- [Django]-Are Django SECRET_KEY's per instance or per app?
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
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
- [Django]-Django multiple template inheritance โ is this the right style?
- [Django]-Multiple Database Config in Django 1.2
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.
- [Django]-How to serve media files on Django production environment?
- [Django]-Function decorators with parameters on a class based view in Django
- [Django]-405 "Method POST is not allowed" in Django REST framework
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.
- [Django]-Cannot set Django to work with smtp.gmail.com
- [Django]-Django: list all reverse relations of a model
- [Django]-How can I handle Exceptions raised by dango-social-auth?
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โฆ
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-Django REST Framework โ 405 METHOD NOT ALLOWED using SimpleRouter
- [Django]-Django middleware difference between process_request and process_view
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.
- [Django]-What is the difference between cached_property in Django vs. Python's functools?
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-Macros in django templates
2๐
I have the similar issue, in my case it was caused by having a Commented script inside the body tag.
<!--<script> </script>-->
- [Django]-POST jQuery array to Django
- [Django]-Django character set with MySQL weirdness
- [Django]-DRF: custom ordering on related serializers
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;
}
- [Django]-How do you use the django-filter package with a list of parameters?
- [Django]-How about having a SingletonModel in Django?
- [Django]-Convert Django Model object to dict with all of the fields intact
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"/> -->
- [Django]-Get count of related model efficiently in Django
- [Django]-Django โ "Incorrect type. Expected pk value, received str" error
- [Django]-Django Rest Framework Conditional Field on Serializer
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.
- [Django]-Django gunicorn sock file not created by wsgi
- [Django]-Error when using django.template
- [Django]-Django count RawQuerySet
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.
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-Django's Double Underscore
- [Django]-What is the Simplest Possible Payment Gateway to Implement? (using Django)
- [Django]-How to make an auto-filled and auto-incrementing field in django admin
- [Django]-Django Framework โ Is there a shutdown event that can be subscribed to?
- [Django]-Inline in ModelForm
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.
- [Django]-*_set attributes on Django Models
- [Django]-Django REST framework post array of objects
- [Django]-Django Multiple Authentication Backend for one project
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.
- [Django]-Charts in django Web Applications
- [Django]-Django Sitemaps and "normal" views
- [Django]-Nginx doesn't serve static
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
- [Django]-Django south migration โ Adding FULLTEXT indexes
- [Django]-Django โ iterate number in for loop of a template
- [Django]-Django connection to postgres by docker-compose
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.
- [Django]-Django TextField and CharField is stripping spaces and blank lines
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-Nginx doesn't serve static
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.
- [Django]-How to add a cancel button to DeleteView in django
- [Django]-Django auto_now and auto_now_add
- [Django]-Row level permissions in django
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.
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-How to save pillow image object to Django ImageField?
- [Django]-Best practices for getting the most testing coverage with Django/Python?
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.
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Serving Media files during deployment in django 1.8
- [Django]-Django: Record with max element
0๐
I had this issue and solved it by removing this line:
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage
- [Django]-How to get getting base_url in django template
- [Django]-How do you use the django-filter package with a list of parameters?
- [Django]-How to stop autopep8 not installed messages in Code
-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
- [Django]-Django: Using F arguments in datetime.timedelta inside a query
- [Django]-South migration: "database backend does not accept 0 as a value for AutoField" (mysql)
- [Django]-What's the idiomatic Python equivalent to Django's 'regroup' template tag?
-5๐
Ok after trying soo many things, the correct solution is โฆ
you need to set DEBUG = 'FALSE'
not False
or FALSE
, but 'FALSE'
with ''
- [Django]-Adding django admin permissions in a migration: Permission matching query does not exist
- [Django]-Django Rest Framework pagination extremely slow count
- [Django]-Group by Foreign Key and show related items โ Django
-7๐
If you want to allow for all hosts.
Use ALLOWED_HOSTS = [โ*โ,]
instead of
ALLOWED_HOSTS = [โ*โ]
- [Django]-How to implement FirebaseDB with a Django Web Application
- [Django]-Many-To-Many Fields View on Django Admin
- [Django]-Error: could not determine PostgreSQL version from '10.3' โ Django on Heroku