Serve Django Static Files with WhiteNoise
Django does not serve static files (CSS, JavaScript, images) in production by default. WhiteNoise is a lightweight middleware that lets your Django application serve its own static files without relying on a separate web server or CDN.
Step 1: Install WhiteNoise
Add whitenoise to your requirements.txt:
whitenoise
Or install it directly:
pip install whitenoise
Step 2: Add WhiteNoise to Middleware
In your settings.py, add WhiteNoise to the MIDDLEWARE list immediately after SecurityMiddleware:
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # Add this line
# ... other middleware
]
The placement matters. WhiteNoise must come directly after SecurityMiddleware so it can intercept requests for static files before they reach other middleware.
Step 3: Configure Static Files Settings
# settings.py
import os
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
# Optional: enable compression and caching
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
CompressedManifestStaticFilesStorage automatically compresses your static files and adds unique hashes to filenames for cache busting. This provides significant performance improvements.
Step 4: Set Your Build Command
In your application's Build Settings, set the build command to collect static files during the build phase:
pip install -r requirements.txt && python manage.py collectstatic --noinput
This ensures all static files are gathered into STATIC_ROOT before the application starts.
Step 5: Deploy
Save your build settings and deploy. WhiteNoise will now serve your static files directly from your Django application.
Verifying It Works
After deployment, open your browser's developer tools and check that CSS and JavaScript files load correctly. You should see 200 responses for your static assets.
If static files return 404 errors, verify that:
collectstaticran successfully during the build (check build logs)STATIC_ROOTpoints to the correct directory- WhiteNoise is in the correct position in
MIDDLEWARE