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 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.
Install the Whitenoise package locally by executing the command below in your terminal.
pip install whitenoise
Go to your project's settings.py and add the app to the installed app list.
INSTALLED_APPS = [
'whitenoise.runserver_nostatic', #add this line
In the middleware section of settings.py add the Whitenoise middleware.
MIDDLEWARE = [
"whitenoise.middleware.WhiteNoiseMiddleware", #add this line
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
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.