How to serve static files in Django using Whitenoise
1 min readSep 5, 2018
This guide walks you through setting up a Django project with WhiteNoise. In most cases it shouldn’t take more than a couple of lines of configuration.
pip install whitenoise
1. Make sure staticfiles is configured correctly
If you’re just getting started with a new Django project then you’ll need add the following to the bottom of your settings.py
file:
# Static files (CSS, JavaScript, Images)STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
2. Enable WhiteNoise
Edit your settings.py
file and add WhiteNoise to the MIDDLEWARE
list.
MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','whitenoise.middleware.WhiteNoiseMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',
]
3. Add compression and caching support
To use it, just add this to your settings.py
:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
As part of deploying your application you’ll need to run python manage.py collectstatic
to put all your static files into STATIC_ROOT
. (If you’re running on Heroku then this is done automatically for you.)
{% load static %}<link rel="stylesheet" type="text/css" href="{% static'css/example.css' %}" />
Done :)