When deploying your Django application to production, it’s important to adjust certain settings to ensure that your application runs securely, efficiently, and reliably. This guide helps prepare Django settings for production with a focus on security, performance, and deployment.
The SECRET_KEY is used for cryptographic signing and must remain private in production.
# Load secret key securely from environment variables
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'default_secret_key')
DEBUG must always be disabled in production to avoid leaking sensitive information.
# Disable debug mode in production
DEBUG = False
Restricts which domains or IPs can serve your Django application.
# Define allowed domains and IP addresses
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com', 'IP_ADDRESS']
Production applications should use robust databases like PostgreSQL or MySQL.
# Configure PostgreSQL database using environment variables
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT', '5432'),
}
}
Static and media files should be served efficiently using dedicated services.
# Configure static and media file locations
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Logging helps track errors and diagnose issues in production.
# Log Django errors to a file
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': '/var/log/django/error.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'ERROR',
'propagate': True,
},
},
}
Enable HTTPS and browser-level protections.
# Enable essential security features for production
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
X_FRAME_OPTIONS = 'DENY'
SECURE_BROWSER_XSS_FILTER = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 3600
Test if your configuration values are ready for production deployment.
? Production Validator
# Load configuration using django-environ
import environ
env = environ.Env()
environ.Env.read_env()
SECRET_KEY = env('DJANGO_SECRET_KEY')
DEBUG = env.bool('DJANGO_DEBUG', default=False)
DATABASES = {
'default': env.db('DATABASE_URL'),
}
Click "Check Production Readiness" above to validate your settings.