How to serve static files in Django using Whitenoise

naufal ihsan
Sep 5, 2018 · 1 min read

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

Source : http://whitenoise.evans.io/en/stable/

naufal ihsan

Written by

I’m not a tech guy

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade