How to serve static files in Django Production with WhiteNoise?

How to serve static files in Django Production with WhiteNoise?

Oh Django, my Django, Love you darling!

Introduction:

You might have faced this situation while deploying your Django project to the production, when the static files were not available after adding DEBUG=False in 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.

Using WhiteNoise:

  • Let’s install it first in our Django project:
pip install whitenoise
  • Modify your settings.py file and add the line given below in your middleware list just after django.middleware.security.SecurityMiddleware
"whitenoise.middleware.WhiteNoiseMiddleware",

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 settings.py files.

    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.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!