Serving Static Files
Gather static assets for production with collectstatic.
Syntax
python manage.py collectstaticThe development server serves static files automatically, but production does not. Set STATIC_ROOT and run collectstatic to copy every app's static files into one folder your web server (or WhiteNoise) can serve.
Example
# settings.py
# STATIC_URL = "/static/"
# STATIC_ROOT = BASE_DIR / "staticfiles"
# Collect all static files into STATIC_ROOT
python manage.py collectstatic --noinput
# WhiteNoise can then serve them from your WSGI app.When to use it
- A developer runs collectstatic as part of a CI/CD pipeline step before deploying a new version to production.
- A team configures WhiteNoise to serve the collected static files directly from Django in a containerized deployment.
- A developer uses the STATICFILES_STORAGE setting to upload collected files to an S3 bucket via django-storages.
More examples
Run collectstatic command
Collects every app's static files into one directory; --noinput skips the confirmation prompt.
python manage.py collectstatic --noinput
# Copies all static files into STATIC_ROOT/Serve statics with WhiteNoise
Inserts WhiteNoise middleware to serve and compress static files directly from Django in production.
# pip install whitenoise
# settings.py
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # second
...
]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"Store statics on S3
Configures django-storages to upload both media files and collected statics to an S3 bucket.
# pip install django-storages boto3
# settings.py
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage"
AWS_STORAGE_BUCKET_NAME = "my-static-bucket"
AWS_S3_REGION_NAME = "us-east-1"
Discussion