Setting DEBUG = False causes 500 Error - django

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', 'xyzadmin#qq.com'),
)
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',
)

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.

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

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.

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)

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

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

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.

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:
...

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.

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

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.

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.

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')

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.

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.

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

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...

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;
}

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"/> -->

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.

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.

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

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.

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.

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

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.

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.

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.

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.

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

Related

Django==2.1 , setting DEBUG to False results in 500 server error [duplicate]

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', 'xyzadmin#qq.com'),
)
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',
)
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.
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',
},
}
}
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.
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)
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
Right, in Django 1.5 if DEBUG = False, configure ALLOWED_HOSTS, adding domains without the port number. example:
ALLOWED_HOSTS = ['localhost']
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.
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:
...
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.
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
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.
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.
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')
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.
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.
I have the similar issue, in my case it was caused by having a Commented script inside the body tag.
<!--<script> </script>-->
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...
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;
}
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"/> -->
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.
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.
this maybe help someone else, in my case the problem with the missing favicon.
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.
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.
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
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.
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.
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.
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.
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

Can't get the TinyMCE to work in django admin

I follow the instruction in here to install the TinyMCE into the django Admin backend.
But it is not working. When checking the console log, I saw this:
http://127.0.0.1:8000/media/js/tiny_mce/tiny_mce.js Failed to load
DO I need to manually adding the js file? The instruction in the github does not mention this.
UPDATE
Indeed to make it work, will have to move the tiny_mce to your static folder.
Here is my solution for anyone who also have similar problem.
settins.py
STATIC_URL = '/static/'
STATIC_ROOT = ''
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
#this is for localhost development, if you are in production enviroment, you will need to remove the STATICFILES_DIRS and define your STATIC_ROOT
TINYMCE_DEFAULT_CONFIG = {
'plugins' : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,pagebreak",
'theme': "advanced",
'theme_advanced_buttons1' : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,fullscreen,code,|,preview,image,media",
'theme_advanced_buttons2' : "table,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,|,forecolor,backcolor, emotions,|,pagebreak,paste",
'theme_advanced_buttons3 ': "",
'theme_advanced_toolbar_location' : "top",
'theme_advanced_toolbar_align' : "left",
'width': '700',
'height': '400'
}
admin.py
class AdminPost(admin.ModelAdmin):
class Media:
js = ('/static/js/tiny_mce/tiny_mce.js',)
Django TinyMCE has the media url as default value, as you can see in the docs:
TINYMCE_JS_URL (default: settings.MEDIA_URL + 'js/tiny_mce/tiny_mce.js')
TINYMCE_JS_ROOT (default: settings.MEDIA_ROOT + 'js/tiny_mce')
If you prefer to use the static files in the static folder, you have to set these values to the correct path. I'd sugest:
TINYMCE_JS_URL = settings.STATIC_URL + 'js/tiny_mce/tiny_mce.js'
TINYMCE_JS_ROOT = settings.STATIC_ROOT + 'js/tiny_mce'
Now you have to ensure you're using the "django.contrib.staticfiles.finders.AppDirectoriesFinder" in your STATICFILES_FINDERS settings, in order to not have to copy the files in development environment, and to be collected with collectstatic.
There are 2 possible reasons for this issue.
1.) You have the required files but on a different location than specified in your script tag. Change the url in your script tag to the valid location and it will work
2.) You do not have the required files. Download the source files and place them in the specified location and it will work.
You should try:-
First uninstalling tinymce
pip uninstall django-tinymce4
and Then re-installing tinymce
It worked for me

Django Admin not working / ugly - serving with nginx and gunicorn

I have nginx, gunicorn, django running on Ubuntu EC2 instance. The entire site operates fine. Except for the admin. The admin isn't displaying properly. I ran "python manage.py collectstatic" and edited the STATIC_ROOT and STATIC_URL. When I load the admin page, it's ugly, but when I inspect the source, the CSS files are located they should be
<title>Site administration | Django site admin</title>
<link rel="stylesheet" type="text/css" href="http://staticfiles.mydomain.com/static/admin/css/base.css" />
<link rel="stylesheet" type="text/css" href="http://staticfiles.mydomain.com/static/admin/css/dashboard.css" />
I can look at the nginx access.log and see the files are getting requested and delivered, but the page does not display properly. It's like the files are being received but not processed. Error log is clean.
SOLVED
Under the console tab in Chrome Developer Tools I noticed the following:
Resource interpreted as Script but transferred with MIME type text/plain: "http://staticfiles.<mydomain>.com/static/admin/js/jquery.min.js".
So the files were getting delivered to browser, but it didn't know what to do with them. To fix it I had to edit the nginx.conf and specify the default type for a couple directories ...
location /static/admin/js/ {
default_type text/javascript;
alias /home/ubuntu/webapps/<myproject>/static/admin/js/;
}
location /static/admin/css/ {
default_type text/css;
alias /home/ubuntu/webapps/<myproject>/static/admin/css/;
}
That fixed it; the django admin loads the stylesheets and javascript files and looks and operates normally. I hope this helps someone else.
My Solve ;
1.step
settings.py edit
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
STATIC_ROOT = "/opt/venv/myDjangoProject/static/"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
2.step
run collesctstatic in terminal :)
python manage.py collectstatic
The proper way to solve this is to add include /etc/nginx/mime.types; in the http section of the nginx configuration file.

How to configure Django's "staticfiles" app to list directory contents?

I'm using Django's built-in web server, in DEBUG mode.
This is part of my settings.py:
STATIC_ROOT = '/home/user/static_root'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/abs/path/to/static/dir',
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
If I access http://localhost:8000/static/png/, I would expect to see a list of files available in /abs/path/to/static/dir/png. Instead I get a 404 error "Directory indexes are not allowed here."
Now if I access the files directly, e.g. http://localhost:8000/static/png/test.png, it works.
I've already checked some answers (here) without success.
So, does anyone know how to configure Django such that the staticfiles app lists directory contents?
Just for completeness since it might help others, this is what I did to solve the problem.
Following #Hedde's answer, I went to use show_indexes:
settings.py
Kept all the configuration the same (i.e. all the STATIC* variables)
Removed 'django.contrib.staticfiles' from INSTALLED_APPS
The problem is that I cannot specify the show_indexes parameter using Django's "built-in" method for static file configuration (via settings.py). By having 'django.contrib.staticfiles' in INSTALLED_APPS, Django would create the static file handler with show_indexes = False, ignoring my urlpatterns.
urls.py
Added the following to urlpatterns:
url(regex = r'^%s(?P<path>.*)$' % settings.STATIC_URL[1:],
view = 'django.views.static.serve',
kwargs = {'document_root': '/abs/path/to/static/dir',
'show_indexes' : True})
'show_indexes': True
As per the documentation
From https://docs.djangoproject.com/en/1.5/ref/views/#django.views.static.serve ...
static.serve(request, path, document_root, show_indexes=True)
Those files are not meant to be served by django. Show indexes is a configuration parameter of apache/nginx.
In production, with nginx, just add to the static serving part :
location ^~ /static/ {
autoindex on;
root /var/www/static_dir;
if ($query_string) {
expires max;
}
}
For dev environnement, Hedde's answer is indeed the good answer, but the display may not be the exact same than the one offered by your HTTP server. Don't rely on it's look&feel.

Django Admin CSS missing

I've been messing around with the new collectstatic command and have got it working for my normal pages. That is to say, I am able to load my css at this location http://localhost:8000/static/css/main.css. However, the css for my django admin doesn't seem to be showing up.
When I navigate to the admin css location at http://localhost:8000/static/admin/css/base.css, I'm getting a 404 page not found with the following error: /home/nai/GitProjects/cats/django-trunk/django/contrib/admin/media/css/base.css" does not exist. Looking in django-trunk, I never had the /home/nai/GitProjects/cats/django-trunk/django/contrib/admin/media/ folder to begin with.
Is that weird?
In any case, in my static folder, there is an admin folder with the accompanying css, img and js folders which was created when I ran collectstatic and the url of the base.css seems to be pointing to that location.
This is happening on my django development server. Here are some snippets to aid in the bug hunt:
urls
33 # In order for Dev Server to serve media files for the frontend site.
34 urlpatterns += staticfiles_urlpatterns()
35
36 try:
37 if settings.DEBUG: # defined in manage.py when the first arg is "runserver"
38 urlpatterns += patterns('',
39 (r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
40 (r'^media-admin/(?P<path>.*)$', 'django.views.static.serve',{'document_root': os.path.join(settings.MEDIA_ROOT, '..', settings.ADMIN_MEDIA_PREFIX)}),
41 )
42 except NameError:
43 pass
I think it might be something to do with line 40 in my URLS file but changing media-admin to static/admin didnt help.
settings
58 ADMIN_MEDIA_PREFIX = '/static/admin'
69 STATIC_ROOT = os.path.join(os.path.abspath(os.path.join(PROJECT_ROOT, '..', MEDIA_DIR, 'static')), '')
70
71 # URL prefix for static files.
72 # Example: "http://media.lawrence.com/static/"
73 STATIC_URL = '/static/'
74
75 # Additional locations of static files. Global files are stored in here
76 STATICFILES_DIRS = (
77 os.path.join(os.path.abspath(os.path.join(PROJECT_ROOT, '..', 'proj_public', 'static', 'proj')), ''),
78 )
79
Django recommends that you deploy static files with a web server other than wsgi.
In settings.py, set:
STATIC_ROOT = 'static'
Run python manage.py collectstatic, which will copy the Django admin static files to /path/to/project/static/
Configure your static file server. If you use Nginx, you could add this config:
location /static/ {
alias /path/to/project/static/;
expires modified +1w;
}
Reload your web server
You should now have access to the static files.
In Django 1.4 ADMIN_MEDIA_PREFIX is deprecated. Here are the steps I followed to catch up with these somewhat recent Django changes:
in settings.py, add django.contrib.staticfiles to INSTALLED_APPS
in settings.py define STATIC_URL — the staticfiles app won't run without it. While using runserver they'll get handled magically, but when you deploy, this needs to be a location where those resources can be fetched by a browser.
I think that's all there was to it.
I'm using Django 1.4.3
What did NOT work for me:
No matter how much I edited ADMIN_MEDIA_PREFIX in settings.py I noticed no change in the HTML generated for the Django Admin pages. It always says /media/admin/base.css when I view the source.
What DID work for me.
Copied the 'admin' folder from /django/contrib/admin/static/ and pasted it into my projects 'media' folder
Now it works great.
It seems dumb, but I actually had this exact issue and the solution was to set DEBUG=False to DEBUG=True on my local dev environment. When debug is set to False, it thinks it's in a production environment which relies on a place to put static files, such as /var/www/html/static, whereas the debug set to True just uses the local directory.
Also make sure that AppDirectoriesFinder is not commented, happens when you're trying to customize your own app structure. Unfortunatelly it's pointless to seek such information in official docs.
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
just change one thing in settings.py
DEBUG = False # not working if you are not serve your static files for production.
just change
DEBUG = True
You need a trailing slash in your ADMIN_MEDIA_PREFIX setting.
Change to:
ADMIN_MEDIA_PREFIX = '/static/admin/'
I'm using chef to auto-build my django server on an AWS Ubuntu server. This post helped, but what I wound up doing was to add the directory to the package admin static pages in a local_setings.py:
https://github.com/jaycrossler/geoq-chef-repo/blob/master/cookbooks/geoq/templates/default/local_settings.py.erb#L16
(added to local_settings.py or to settings.py):
STATICFILES_DIRS = ('<%= node['geoq']['virtualenv']['location'] %>/local/lib/python2.7/site-packages/django/contrib/admin/static/',)
This resulted in local_settings.py having:
STATICFILES_DIRS = ('/var/lib/geoq/local/lib/python2.7/site-packages/django/contrib/admin/static/',)
Note, that if you have other items already in your STATICFILES_DIRS, you might want to append to the list, rather than overwriting it.
in my project, the solution is in settings.py, set:
DEBUG = False # debug false mod not working css
One solution might be to add your local IP to the ALLOWED_HOSTS list in settings.py
e.g.
CURRENT_IP = '192.168.0.123'
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '0.0.0.0', CURRENT_IP]
you need
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I don't know how it was resolved, but I took these steps when I encountered the same problem. I simply add these line in settings.py.
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','compressor.finders.CompressorFinder', )
i hope this will help you all.
In settings.py
Don't use tuple for the
STATICFILES_DIRS =(
os.path.join(BASE_DIR, 'static'),
)
you should use list,like this
STATICFILES_DIRS =[
os.path.join(BASE_DIR, 'static'),
]