When deploying Django in production, it’s essential to configure security settings to protect both the application and its users. Django provides many built-in security features, but they must be explicitly enabled and tuned for real-world environments.
Django security is primarily configured in the settings.py file. These settings control how requests, responses, cookies, and headers behave in production environments.
# Disable debug mode to avoid leaking sensitive information
DEBUG = False
# Restrict domains that can serve this Django application
ALLOWED_HOSTS = ['yourdomain.com', 'sub.yourdomain.com']
# Force cookies and requests to use HTTPS
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
# Enforce HTTPS for one year using HSTS
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# Prevent browsers from guessing content types
SECURE_CONTENT_TYPE_NOSNIFF = True
# Enable built-in browser XSS filtering
SECURE_BROWSER_XSS_FILTER = True
# Disallow embedding this site in iframes
X_FRAME_OPTIONS = 'DENY'
# Configure Content Security Policy using django-csp
INSTALLED_APPS = ['csp']
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", 'https://trusted-cdn.com')
Toggle the settings below to simulate how they affect your Django application's security posture.