Production Configuration
Production-ready Django-CFG configuration demonstrating all features, security best practices, and real-world patterns.
Security First Production configuration requires careful attention to secrets management, SSL/TLS, and security headers. Never commit secrets to version control.
Minimal Production Setup
Production Deployment Checklist CRITICAL: Before deploying to production, verify ALL of these:
- 🔒 DEBUG = False - Never run with DEBUG=True in production
- 🔒 Strong SECRET_KEY - At least 50 random characters
- 🔒 Reverse proxy SSL - nginx/Cloudflare handles HTTPS
- 🔒 Secrets from environment - No hardcoded credentials
- 🔒 Database SSL - Encrypted database connections
- 🔒 security_domains set - Production domains configured
- 🔒 Static files collected - Run collectstatic before deploy
Start Simple Start with minimal configuration and add features as needed. This prevents configuration bloat and reduces attack surface.
Minimal Config
from django_cfg import DjangoConfig, DatabaseConfig
from .environment import env
class ProductionConfig(DjangoConfig):
# Project basics
project_name: str = env.app.name
project_version: str = env.app.version
# Security
secret_key: str = env.secret_key
debug: bool = False
# ssl_redirect: Optional - not specified (defaults to None)
# Assumes reverse proxy (nginx/Cloudflare) handles SSL
security_domains: list[str] = env.security.domains
# Media files - CDN for production
media_url: str = env.media_url # e.g., "https://cdn.example.com/media/"
# Database from environment
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url(url=env.database.url)
}
config = ProductionConfig()Environment Variables
SECRET_KEY=... # from your secrets manager
DJANGO_ENV=production
DATABASE_URL=... # from your secrets managerThe env object is your own pydantic-settings loader (see Environment Setup). django-cfg itself reads only DJANGO_ENV, DJANGO_CFG_BANNER and the DJANGO_CFG_LOG_* variables.
Environment Variables Always use environment variables for secrets in production. Never hardcode sensitive values in config files.
Complete Production Configuration
Configuration Complexity This complete example shows all available features. For most production deployments, start with the minimal setup above and add features incrementally as needed. Unnecessary features increase attack surface and maintenance burden.
# config.py
from django_cfg import (
DjangoConfig,
DatabaseConfig,
CacheConfig,
EmailConfig,
AdminSiteConfig,
SpectacularConfig,
TelegramConfig,
DjangoRQConfig,
ApiKeys,
)
from .environment import env
class MyProductionConfig(DjangoConfig):
"""
Production configuration with all Django-CFG features.
Environment-aware, type-safe, and production-ready.
"""
# === Project Metadata ===
project_name: str = env.app.name
project_version: str = env.app.version or "1.0.0"
project_description: str = env.app.description or ""
# === Security Settings ===
secret_key: str = env.secret_key
debug: bool = env.debug
# ssl_redirect: Optional - not specified (reverse proxy handles SSL)
security_domains: list[str] = env.security.domains
# === Custom Applications ===
project_apps: list[str] = [
"core",
"apps.users",
"apps.api",
# Add your apps here
]
# === Database Configuration ===
databases: dict[str, DatabaseConfig] = {
# Primary database
"default": DatabaseConfig.from_url(
url=env.database.url,
sslmode="require" if env.is_production else "prefer",
connect_timeout=10,
),
}
# === Cache Configuration ===
# Just set redis_url: the cache is created from it
redis_url: str | None = env.redis.url
# Django-CFG automatically creates CacheConfig with:
# - timeout=300 (5 minutes)
# - key_prefix=project_name.lower() with spaces replaced by _
# - max_connections=50
# Override with explicit cache_default if needed
# === Email Configuration ===
email: EmailConfig | None = (
EmailConfig(
backend="django.core.mail.backends.smtp.EmailBackend",
host=env.email.host,
port=env.email.port,
username=env.email.user,
password=env.email.password,
use_tls=True,
default_from=env.email.from_email,
)
if env.email.enabled
else None
)
# === Telegram Configuration ===
telegram: TelegramConfig | None = (
TelegramConfig(
bot_token=env.telegram.bot_token,
chat_id=env.telegram.chat_id,
)
if env.telegram.enabled
else None
)
# === Background Tasks (Django-RQ) ===
django_rq: DjangoRQConfig | None = (
DjangoRQConfig(
queues=env.tasks.queues or ["default", "high", "low"],
)
if env.redis.url
else None
)
# === Admin Interface ===
admin_site: AdminSiteConfig | None = AdminSiteConfig(
site_title=f"{env.app.name} Admin",
site_header=f"{env.app.name} Administration",
)
# === API Documentation ===
spectacular: SpectacularConfig | None = SpectacularConfig(
title=f"{env.app.name} API",
description=env.app.description or "API Documentation",
version=env.app.version or "1.0.0",
)
# === API Keys (from environment) ===
api_keys: ApiKeys | None = ApiKeys(
openai=env.api_keys.openai,
openrouter=env.api_keys.openrouter,
)
# Create and set configuration
config = MyProductionConfig()Environment Configuration
NEVER Commit .env Files Critical security rule: Environment files contain production secrets and MUST NEVER be committed to version control.
Add to .gitignore:
# Environment files
.env
.env.*
env.production
# But keep examples
!.env.exampleInstead:
- ✅ Use
.env.examplewith placeholder values - ✅ Document required variables in README
- ✅ Use secret management systems (AWS Secrets Manager, HashiCorp Vault)
- ✅ Set environment variables in deployment platform
# .env.production (never committed; values come from your secrets manager)
DJANGO_ENV=production
SECRET_KEY=...
DATABASE_URL=...
REDIS_URL=...
EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
EMAIL_USER=...
EMAIL_PASSWORD=...
TELEGRAM_BOT_TOKEN=...
TELEGRAM_CHAT_ID=...
OPENAI_API_KEY=...Read these in your own pydantic-settings loader (the env object in the examples above); django-cfg does not read them directly.
Multi-Environment Setup
Environment Strategy Use separate configuration classes for each environment to ensure proper isolation and prevent production mistakes.
Development
class DevelopmentConfig(DjangoConfig):
debug: bool = True
# security_domains: Optional - not needed in development
# Django-CFG auto-allows localhost on any port
# SQLite for development
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url("sqlite:///dev.db") # relative to the project
}DEBUG=True is DANGEROUS in Production Never run with DEBUG=True in production. It exposes:
- 🔓 Full stack traces - Reveals source code paths and logic
- 🔓 Environment variables - Shows SECRET_KEY and credentials
- 🔓 SQL queries - Exposes database structure and data
- 🔓 Internal paths - File system layout and dependencies
- 🔓 Library versions - Makes exploit targeting easier
Performance impact:
- Templates not cached - Every request recompiles
- Static files served by Django - Slow, not production-ready
- Query logging enabled - Memory leaks over time
Development Benefits Development environment enables all features for testing, uses SQLite for simplicity, and disables SSL redirect for local testing.
Staging
class StagingConfig(DjangoConfig):
debug: bool = False
security_domains: list[str] = ["staging.myapp.com"]
# PostgreSQL from environment
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url(env.database.url)
}Staging Purpose
Staging mirrors production settings but with reduced feature set for focused testing before production deployment.
Production
class ProductionConfig(DjangoConfig):
debug: bool = False
security_domains: list[str] = env.security.domains
# Production database with replicas
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url(
env.database.url,
sslmode="require",
operations=["write", "migrate"],
),
"read_replica": DatabaseConfig.from_url(
env.database.replica_url,
operations=["read"],
migrate_to="default",
),
}operations and migrate_to describe intent; the generated router does not enforce them. Pin a read replica yourself with .using("read_replica"), or add your own router.
Production Deployment Checklist Before deploying ProductionConfig, verify:
- ✅
debug = Falsealways - ✅
security_domainsconfigured with production domains - ✅ Reverse proxy (nginx/Cloudflare) handles SSL/TLS
- ✅ SSL required for databases (
sslmode=require) - ✅ Read replicas configured for scalability
- ✅ Feature flags from environment (not hardcoded)
- ✅ Static files collected:
python manage.py collectstatic --noinput - ✅ Migrations applied:
python manage.py migrate --noinput - ✅ Health check working:
/healthzreturns 200 OK - ✅ Logs configured: Check application writes to production logs
- ✅ Secrets validated: All required environment variables set
Configuration Selection
Wrong Environment = Production Disaster Loading the wrong configuration can cause catastrophic failures:
- ❌ Development config in production → Exposed debug info, disabled security
- ❌ Production config in development → Data corruption in wrong database
- ❌ Missing environment variable → Application crash on startup
Always validate environment selection:
# Fail fast if environment is wrong
if env.environment not in CONFIG_MAP:
raise ValueError(f"Invalid environment: {env.environment}")
# Validate production safeguards
if env.environment == "production" and config.debug:
raise ValueError("DEBUG cannot be True in production!")# config.py
from django_cfg import DjangoConfig
from .environment import env
# Define all configurations
class DevelopmentConfig(DjangoConfig):
...
class StagingConfig(DjangoConfig):
...
class ProductionConfig(DjangoConfig):
...
# Select configuration based on environment
CONFIG_MAP = {
"development": DevelopmentConfig,
"staging": StagingConfig,
"production": ProductionConfig,
}
# Validate environment
if env.environment not in CONFIG_MAP:
raise ValueError(
f"Invalid environment '{env.environment}'. "
f"Must be one of: {list(CONFIG_MAP.keys())}"
)
config = CONFIG_MAP[env.environment]()
# Final production validation
if env.environment == "production":
if config.debug:
raise ValueError("CRITICAL: DEBUG=True in production!")
if len(config.secret_key) < 50:
raise ValueError("CRITICAL: SECRET_KEY too short for production!")
if not config.security_domains:
raise ValueError("CRITICAL: security_domains not configured!")Security Best Practices
Critical Security Requirements Production applications must implement all security best practices below. Skipping any of these increases vulnerability to attacks.
1. Secret Management
Validate Secrets
import os
from django_cfg import DjangoConfig
class SecureConfig(DjangoConfig):
# Fail fast if missing
secret_key: str = os.environ["SECRET_KEY"]
def model_post_init(self, __context) -> None:
super().model_post_init(__context)
if len(self.secret_key) < 50:
raise ValueError("SECRET_KEY too short")In production debug is forced to False for you (with a UserWarning), so you do not need to check it yourself.
Secret Key Length
Django’s SECRET_KEY must be at least 50 characters long and cryptographically random. Use django.core.management.utils.get_random_secret_key() to generate.
Secret Storage
✅ Recommended:
# Environment variables
export SECRET_KEY="your-secret-key-here"
export DATABASE_URL="postgresql://..."❌ Never do this:
# DON'T hardcode secrets in config files
secret_key: str = "my-secret-key-123" # ❌ WRONGSecret Leaks Hardcoded secrets in files can be leaked through:
- Git history (even after deletion)
- Log files
- Error messages
- Backup systems
Secret Rotation
Rotate secrets by changing the environment value and redeploying. Changing SECRET_KEY invalidates existing sessions and signed tokens, so schedule it.
Rotation Strategy
Rotate secrets regularly (every 90 days) and plan for the session invalidation that a new SECRET_KEY causes.
2. Database Security
SSL Required Always use SSL/TLS for database connections in production. Unencrypted connections expose credentials and data.
SSL Configuration
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig(
sslmode="require", # Force SSL
connect_timeout=10, # Timeout protection
options={
"options": "-c statement_timeout=30000", # 30s query timeout
},
)
}Credential Management
# Use DATABASE_URL from environment
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url(
url=os.environ["DATABASE_URL"],
sslmode="require",
)
}Connection Strings Never log database URLs - they contain credentials. Ensure logging filters strip passwords.
3. CORS & Security Headers
Security Headers Django-CFG configures security headers in production mode. Manual configuration rarely needed.
class SecureConfig(DjangoConfig):
security_domains: list[str] = [
"myapp.com", # ✅ Flexible format
"https://api.myapp.com", # ✅ With protocol
"www.myapp.com:8443", # ✅ With port
]
# ssl_redirect: Optional - not needed (reverse proxy handles SSL)
# Custom request headers need no setup (preflights from trusted origins are
# answered with the requested headers). To list one explicitly:
cors_extra_headers: list[str] = ["x-holder"]Do not set cors_allow_headers just to add a header: it replaces the default list. See CORS.
Auto-configured Security Headers
In production mode (debug=False), Django-CFG automatically enables:
SECURE_SSL_REDIRECT = False- Reverse proxy handles redirectsSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')- Trust proxySECURE_HSTS_SECONDS = 31536000- Force HTTPS for 1 yearSECURE_HSTS_INCLUDE_SUBDOMAINS = True- Apply to subdomainsSECURE_CONTENT_TYPE_NOSNIFF = True- Prevent MIME sniffingX_FRAME_OPTIONS = "DENY"- Prevent clickjackingSECURE_BROWSER_XSS_FILTER = True- Enable XSS protection
Media Files Configuration
Production Media Strategy
Two separate decisions: where files are stored (storage.backend) and the
URL they are served from (media_url). Local disk does not survive a
container restart, so production should store uploads in object storage — see
Object storage below.
Media URL Options
class ProductionConfig(DjangoConfig):
# Option 1: CDN (recommended for production)
media_url: str = "https://cdn.example.com/media/"
# Option 2: Auto-generate from api_url
media_url: str = "__auto__" # → https://api.example.com/media/
# Option 3: Relative URL (served by Django/nginx)
media_url: str = "/media/" # DefaultEnvironment Configuration
# Production - CDN
MEDIA_URL="https://cdn.example.com/media/"
# Or auto-generate from API URL
MEDIA_URL="__auto__"Object storage
media_url only controls the URL files are served from. To also store
uploads in object storage — so they survive a container restart — configure
storage.backend. django-cfg generates STORAGES for you; there is no need to
set DEFAULT_FILE_STORAGE or AWS_* settings by hand.
from django_cfg import DjangoConfig, StorageConfig, S3StorageConfig
class ProductionConfig(DjangoConfig):
storage: StorageConfig = StorageConfig(
backend=S3StorageConfig.r2(
account_id="abc123",
bucket_name="media",
custom_domain="media.example.com",
),
)# Credentials — no keys in code
R2__ACCESS_KEY_ID="your-access-key"
R2__SECRET_ACCESS_KEY="your-secret-key"Setting custom_domain rewrites MEDIA_URL automatically, so you do not set it
separately. Presets exist for AWS S3 and MinIO too. Requires
pip install django-cfg[s3].
Full setup, credentials, and the R2-specific gotchas (the 501 Not Implemented
checksum error in particular) are on the
Media Storage page.
Nginx (self-hosted)
# config.py - Let nginx serve media
media_url: str = "/media/" # Relative URL# nginx.conf
location /media/ {
alias /var/www/media/;
expires 30d;
add_header Cache-Control "public, immutable";
}Django Serves Media Only in Development
When media_url is an absolute URL (starts with http:// or https://), Django-CFG automatically skips adding local media serving routes. Media files must be served by your CDN or reverse proxy.
Performance Optimization
Performance Best Practices Proper configuration of database pooling, caching, and task queues is critical for production performance at scale.
Database Pooling
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig(
# ...engine, name, host as usual...
conn_max_age=600, # reuse a connection for up to 10 minutes
conn_health_checks=True, # drop a dead connection before use
connect_timeout=10, # connection timeout, seconds
)
}Connection Pool Sizing
Each worker process holds its own connections, so size the pooler (PgBouncer) or database max_connections for processes x conn_max_age reuse, not for request count. For cloud databases, limit connections to avoid quota exhaustion.
Cache Configuration
# Cache created from redis_url
redis_url: str = env.redis.url
# Django-CFG automatically creates CacheConfig with sensible defaults:
# - timeout=300 (5 minutes)
# - key_prefix=project_name.lower()
# - max_connections=50Automatic Cache Creation
Set redis_url and Django-CFG creates the default cache. Use cache_default=CacheConfig(...) only to change the defaults.
Cache Strategy
- Short TTL (1-5 min): Dynamic content, user sessions
- Medium TTL (5-60 min): API responses, computed data
- Long TTL (1+ hours): Static content, reference data
Task Queues
django_rq: DjangoRQConfig = DjangoRQConfig(
queues=["default", "high", "low", "emails", "reports"],
)Queue Design Separate queues by priority and characteristics:
- high: Critical tasks (payments, notifications)
- default: Regular background tasks
- low: Bulk operations, cleanup
- emails: Email sending (dedicated workers)
Advanced Performance Tuning
Read Replicas
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url(
env.database.url,
operations=["write", "migrate"],
),
"read_replica_1": DatabaseConfig.from_url(
env.database.replica_1_url,
operations=["read"],
),
"read_replica_2": DatabaseConfig.from_url(
env.database.replica_2_url,
operations=["read"],
),
}Cache Layering
# Multiple cache backends
CACHES = {
"default": { # Redis for session/general
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": env.redis.url,
},
"local": { # Local memory for hot data
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "unique-snowflake",
},
}Monitoring & Logging
Production Observability Production systems require comprehensive logging, monitoring, and alerting to ensure reliability and quick incident response.
Logging Configuration
django-cfg generates the whole logging path (one root handler, repeat collapsing, request ids, secret masking). Tune it through the logging field and DJANGO_CFG_LOG_* variables instead of writing a LOGGING dict. See Logging in production.
class MonitoredConfig(DjangoConfig):
# Minimal startup output: a quiet single line unless DJANGO_CFG_BANNER=1
startup_banner: bool = False
telegram: TelegramConfig = TelegramConfig(
bot_token=env.telegram.bot_token,
chat_id=env.telegram.admin_chat,
)Log files are opt-in (DJANGO_CFG_LOG_DIR), with rotation built in (logging.rotate_mb, logging.backups). Production logs go to stdout for your platform to collect.
Health Monitoring
django-cfg serves /healthz (liveness) and /healthz/ready (database, cache, system, configuration) from the always-installed health app, so you do not write a health view. See Monitoring.
Health Check Endpoint
Point Kubernetes, AWS ELB or your uptime monitor at /healthz, and use /healthz/ready for readiness.
Alert Configuration
# Telegram alerts for critical events
telegram: TelegramConfig = TelegramConfig(
bot_token=env.telegram.bot_token,
chat_id=env.telegram.admin_chat,
dedupe=True, # identical messages inside the window are sent once
dedupe_window_seconds=60,
)Pass dedupe=False to a single call to force a repeat. Amounts and ids in a message are not folded, so two different payments are never merged.
Alert Channels
Common alert channels for production:
- Telegram: Real-time notifications
- Email: Detailed error reports
- Slack: Team collaboration
- PagerDuty: On-call rotation
See Also
Deployment & Production
Production Setup:
- Docker Deployment - Containerized production deployment
- Multi-Database Setup - Advanced database configuration
- Logging Configuration - Structured logging setup
- Health Monitoring - System health checks
Configuration:
- Configuration Guide - Configuration setup
- Configuration Models - Complete config API
- Environment Detection - Auto-detect environments
- Environment Variables - Secure credential management
Security & Performance
Security:
- Security Settings - CORS, CSRF, SSL/TLS hardening
- Type-Safe Configuration - Pydantic validation
Performance:
- Cache Configuration - Redis, Memcached setup
- Background Tasks - Async processing
- Database Optimization - Connection pooling, read replicas
Features & Integration
Built-in Features:
- Built-in Apps Overview - Production-ready apps
Integration:
- API Generation - Auto-generate API clients
Tools & Support
CLI Tools:
- CLI Introduction - Command-line tools
- Core Commands - Validation and deployment commands
Support:
- Troubleshooting - Common production issues
- Migration Guide - Migrate to production
- FAQ - Frequently asked questions
Note: The env object in these examples is your own pydantic-settings loader. See Configuration Guide for complete setup.