How to setup Whitenoise for a Django project
Hello, welcome to the devmaesters website. In this post I am going to show you how you can setup Whitenoise in your Django project to serve your staticfiles in a production environment.
Whitenoise
Whitenoise is a very usefull pip package that allows you to configure your Django project to serve its own staticfiles so it can deploy anywhere without depending on service providers.
Follow the steps below to setup Whitenoise in your Django project.
Step 1
Install the Whitenoise package locally by executing the command below in your terminal.
pip install whitenoise
Step 2
Go to your project's settings.py and add the app to the installed app list.
INSTALLED_APPS = [
'django.contrib.staticfiles',
'whitenoise.runserver_nostatic', #add this line
]
Step 3
In the middleware section of settings.py add the Whitenoise middleware.
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", #add this line
]
Step 4
Add this line to your settings.py file
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_STORAGE="whitenoise.storage.CompressedManifestStaticFilesStorage"#add this line
Conclusion
And that's it, following the steps listed above will make it easy to enable staticfiles on hosting platform that require you to serve your own staticfiles e.g Heroku and Railway.