0
0
Djangoframework~5 mins

WhiteNoise for static files in Django

Choose your learning style9 modes available
Introduction

WhiteNoise helps your Django app serve static files like images and CSS easily without needing a separate web server.

You want to serve CSS and JavaScript files in a simple Django project.
You are deploying your Django app to a platform without a dedicated static file server.
You want faster static file serving during development and production.
You want to avoid configuring complex web servers like Nginx just for static files.
Syntax
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    # other middleware
]

STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/static/'

# Optional: Enable compression and caching
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Add WhiteNoiseMiddleware right after SecurityMiddleware in your MIDDLEWARE list.

Set STATIC_ROOT to the folder where static files will be collected.

Examples
This shows where to place WhiteNoise middleware in the middleware list.
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # other middleware
]
This setting enables compression and caching for static files to improve performance.
Django
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Sample Program

This example shows a minimal Django setup using WhiteNoise to serve a CSS file from the static folder.

Django
from django.http import HttpResponse
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

# Simple view

def home(request):
    return HttpResponse('<html><head><link rel="stylesheet" href="/static/style.css"></head><body><h1>Hello with WhiteNoise!</h1></body></html>')

urlpatterns = [
    path('', home),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

# settings.py snippet
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    # other middleware
]

STATIC_URL = '/static/'
STATIC_ROOT = '/path/to/staticfiles'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
OutputSuccess
Important Notes

Run python manage.py collectstatic to gather all static files into STATIC_ROOT.

WhiteNoise works well for small to medium projects but for very large sites, a dedicated static file server is better.

Summary

WhiteNoise lets Django serve static files simply without extra servers.

Add WhiteNoise middleware after SecurityMiddleware in settings.

Use collectstatic to prepare static files for WhiteNoise.