You might have faced this situation while deploying your Django project to the production, when the static files were not available after adding
settings.py file. Because Django is not capable of serving the static files in production.
In that case, you have few ways to fix the static file issue, such as:
- Using Nginx/Apache to serve static files.
- Using an Object storage such as AWS S3 to server the static files.
- Using WhiteNoise to serve the static files via Django itself.
- Let’s install it first in our Django project:
pip install whitenoise
- Modify your
settings.pyfile and add the line given below in your middleware list just after
So your middleware will look something like this now:
MIDDLEWARE = [ # Other middlewares... "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", # Other middlewares... ]
The last step (Optional) is to add a new storage backend for static files. WhiteNoise has a nice storage backend which will take care of Compressing and Caching for you. Let’s add this line at the end of our
We get two storage backends from WhiteNoise, we can use any one of them.
# If you just want compression STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
# If you want compression with caching STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
You are all set now. Deploy your project and Enjoy!
For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.