[Django]-Django – CSS File Not Loading In Production (Debug: False)

8👍

You are using Django’s development server with Debug=False. Django will not serve static content when Debug is False.

Django development server is not intended to be used in production.

You will need a Web Server which will serve your static content (or put it on a CDN)

Common deployment styles used with Django are

nginx -> uwsgi -> django


apache -> mod_wsgi -> django


There’s also gunicorn which is relatively easier to set up.

👤at14

4👍

By default, when DEBUG = False in production, django will not serve static files.

To change this behavior

After deploying your application you’ll need to run python manage.py collectstatic to put all your static files into STATIC_ROOT.

I introduce Whitenoise which allows your web app to serve its own static files. It works with any WSGI-compatible app.

To install it run:

pip install whitenoise

Edit your settings.py file and add WhiteNoise to the MIDDLEWARE_CLASSES list, above all other middleware apart from Django’s SecurityMiddleware:

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  # ...
]

Save and restart your server

Finaly if you want gzip functionality, add this to your settings.py

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

save and restart

2👍

The above answer is not entirely true… There’s another way! Took me forever to figure out 🙁

Step 1: If you are/were using them, make sure that all traces of WhiteNoise and django_heroku are removed: from imports, INSTALLED_APPS, virtual environment, etc.

Step 2:

STATIC_URL = '/static/'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "path/to/other/static/dir"),
]

The key for me was using the proper storage engine which is set by STATICFILES_STORAGE.
You don’t need to set STATIC_ROOT because the root will be generated for you by the engine. More on that in the warning section here: https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-STATIC_ROOT

DEBUG = False 
ALLOWED_HOSTS = ['127.0.0.1']

Then finally

$ python manage.py collectstatic
$ python manage.py runserver

If this doesn’t help, don’t forget logging: With DEBUG=False, how can I log django exceptions to a log file

This kind of helped: https://docs.djangoproject.com/en/1.11/howto/static-files/

👤valem

Leave a comment