Handling Django Static Files in Production
Anthony Herbert
The Django development server makes it easy to work with static files. Any static files in static folders across your app just work when you reference them with the {% static %} tag in your templates. But you will find that when you deploy with a production app server like gunicorn, your static files no longer work. In this short article, I'm going to tell you the easiest way to get your static files working in production.
In a production environment, the normal recommendation is to put your static files behind a web server or in an object storage. Those options do work well, but they take more work to set up than the approach I'm about to tell you. Instead of placing your static files in a different location, you can continue to leave them in your static directories and have them served automatically with just a little bit of configuration.
To get this to work, you can use a library called Whitenoise. This library will take files in your static root and serve them in response to the URLs for those static files. To get started with Whitenoise, first you need to install it and add it to your requirements.
pip install whitenoise
pip freeze > requirements.txt
Then in your settings.py file, add the Whitenoise middleware to your settings.
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
Finally, make sure you have a STATIC_ROOT defined in your settings.py so when you run manage.py collectstatic all of your static files will be placed in one location for Whitenoise to serve them.
# settings.py
STATIC_ROOT = BASE_DIR / 'staticfiles'
That's it! Once your app is deployed to production, just run manage.py collectstatic and your files will automatically be served for you just like they were by the Django development server.