Configuration Models
Django-CFG uses Pydantic v2 models for type-safe, validated configuration.
Why Type-Safe Configuration?
Type-safe configuration catches errors at startup instead of runtime, provides IDE autocomplete, and enables static type checking with mypy/pyright. DjangoConfig forbids unknown fields, so a misspelled option is an error, not a silent no-op.
Quick Start
from django_cfg import DjangoConfig, DatabaseConfig
class MyProjectConfig(DjangoConfig):
project_name: str = "My Project"
secret_key: str = "x" * 50 # min 50 characters; read it from the environment in real code
debug: bool = True
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url(url="sqlite:///db/default.sqlite3"),
}
# Optional services are config sections:
# email: EmailConfig = EmailConfig(...)
# telegram: TelegramConfig = TelegramConfig(...)
config = MyProjectConfig()Values come from your own code or an environment loader (pydantic-settings is the recommended one, see Getting Started: Configuration). django-cfg itself does not read YAML files.
Configuration Topics
Core Configuration
- DjangoConfig - Base configuration class
- Security Settings - Security, CORS, SSL; hosts derived from
sites,api_urlandsecurity_domains - Environment - Environment detection and variables
- Sites - Deployment and sites: which field owns what, one site by default, several with
sites
Infrastructure
- Database - Database configuration
- Cache - Default cache created from
redis_url(Redis, LocMem, Dummy) - Media Storage - S3-compatible object storage (Cloudflare R2, MinIO, AWS S3)
- Logging - Logging configuration
Deployment
- Docker Configuration - Environment variables and layered config for Docker
Services
Security
- Two-Factor Authentication - TOTP-based 2FA configuration
Django Integrations
- Admin & UI - Admin site: stock Django admin, navigation, theme
- API - DRF, Spectacular, JWT
Key Features
Type Safety
class MyConfig(DjangoConfig):
debug: bool = True
# This works
config = MyConfig(project_name="App", secret_key="x" * 50, debug=True)
# This fails with a validation error
config = MyConfig(project_name="App", secret_key="x" * 50, debug="maybe")See validation error output
ValidationError: 1 validation error for MyConfig
debug
Input should be a valid boolean [type=bool_parsing]Environment Variables
Read them with a pydantic-settings loader and pass the values in:
from pydantic_settings import BaseSettings, SettingsConfigDict
class EnvironmentConfig(BaseSettings):
secret_key: str
redis_url: str | None = None
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
env = EnvironmentConfig()Environment Variables in Production Always use environment variables for secrets (API keys, passwords) in production. Never commit them to version control.
Validation
from pydantic import Field, field_validator
class MyConfig(DjangoConfig):
max_connections: int = Field(default=100, ge=1, le=1000)
@field_validator('secret_key')
@classmethod
def validate_secret_key(cls, v):
if v.startswith("changeme"):
raise ValueError("Please change the default secret key")
return vValidators run during instantiation.
Configuration Patterns
Development vs Production
env_mode (development, production, test) is a field of DjangoConfig; use is_development, is_production and is_test instead of re-deriving it.
class MyConfig(DjangoConfig):
@property
def database_url(self) -> str:
if self.is_production:
return "postgresql://prod-db/main"
return "sqlite:///db/dev.sqlite3"Separate Configs
import os
class BaseConfig(DjangoConfig):
project_name: str = "My Project"
class DevConfig(BaseConfig):
debug: bool = True
class ProdConfig(BaseConfig):
debug: bool = False
config = (ProdConfig if os.getenv("DJANGO_ENV") == "production" else DevConfig)(secret_key=os.environ["SECRET_KEY"])Optional Features
Optional features are Optional[...] config sections that are None (off) until you set them:
from typing import Optional
from django_cfg import EmailConfig, TelegramConfig
class MyConfig(DjangoConfig):
email: Optional[EmailConfig] = EmailConfig(
backend="smtp",
host="smtp.example.com",
username="apikey",
password="...",
default_from="[email protected]",
)
telegram: Optional[TelegramConfig] = NoneSee Also
- Type-Safe Configuration - Why type safety matters
- Environment - Environment variables and detection
- Database - Database configuration details
- Docker Configuration - Layered config strategy for Docker
- Docker Overview - Complete Docker deployment guide