Django-CFG System Architecture
Django-CFG uses Pydantic v2 models to provide type-safe Django configuration with validation at startup.
Architecture Philosophy Django-CFG is a layered package with a lazy public facade, fail-fast validation and zero-configuration defaults.
Architecture Overview
Django-CFG transforms a Pydantic model into Django settings in a few stages:
Core Design Principles
- Type safety: all configuration is Pydantic models (
extra="forbid", so a misspelled field fails) - Fail-fast: configuration errors are raised when the config is instantiated, not during requests
- Environment-aware:
env_modeplusDJANGO_ENV/ENVIRONMENT/ENVselect dev, test or production defaults - Lazy facade:
import django_cfgstays light; heavy modules load on first use - Layered: each layer imports only downward (enforced by import-linter, see below)
Package Layout
django_cfg/
core/ DjangoConfig, builders, generators, environment detection, startup
models/ Pydantic config models (infrastructure, api, django, services)
modules/ feature modules (django_email, django_telegram, django_rq, django_llm, ...)
apps/ built-in Django apps (system/accounts, totp, mailer, tools/*, payments, api)
middleware/ middleware and pagination classes
mixins/ reusable model and view mixins
management/ manage.py commands
cli/ the django-cfg command1. Core layer (django_cfg/core/)
from django_cfg import DjangoConfig
class MyConfig(DjangoConfig):
project_name: str = "My App"
secret_key: str = "..."
config = MyConfig()
settings = config.get_all_settings() # complete Django settings dictDjangoConfig is defined in core/base/config_model.py (data model only). Logic lives beside it:
core/builders/-apps_builder.py(INSTALLED_APPS),middleware_builder.py(MIDDLEWARE),security_builder.pycore/generation/- generators for databases, cache, email, logging, DRF, RQ, OAuth and the rest of the settingscore/environment/- environment detectioncore/integration/- URL integration, startup display, version checkcore/state/-set_current_config()/get_current_config()
See Builder Pattern and Generator Pattern.
2. Public facade (django_cfg/__init__.py)
The facade exports an explicit __all__. Most names are imported eagerly from light modules.
Only names that read Django settings at import time (DRF pagination classes, django_import_export
classes, check_python_version) are resolved lazily through a module-level __getattr__:
from django_cfg import DjangoConfig, DatabaseConfig # light, eager
from django_cfg import DefaultPagination # lazy: loaded on first accessA test (tests/test_public_api.py) pins __all__ against a snapshot, and
tests/test_import_budget.py keeps the cost of import django_cfg bounded. See Registry.
3. Pydantic models (django_cfg/models/)
Type-safe configuration models that replace Django’s raw dictionaries:
models/infrastructure/-DatabaseConfig,CacheConfig,SecurityConfig,LoggingConfigmodels/api/-JWTConfig,DRFConfig, OAuth,LimitsConfig,TwoFactorConfig, CORS and rate limitingmodels/django/-RQ,Constance,Currency,Geo,Storage,Payments,Site,OpenAPIClientConfigand similarmodels/services/-EmailConfig,TelegramConfig
from django_cfg import DatabaseConfig
db = DatabaseConfig.from_url("postgresql://user:pass@localhost:5432/app")
db.to_django_config() # Django DATABASES entry4. Built-in apps (django_cfg/apps/)
| Path | What it provides |
|---|---|
apps/system/accounts | Custom user model, OTP and OAuth sign-in |
apps/system/totp | Two-factor authentication |
apps/system/mailer | Mail delivery and templates |
apps/tools/{geo,currency,analytics,chat} | Geo data, currency rates, analytics, chat |
apps/payments | Payments |
apps/api | Health and endpoint status API |
accounts, totp and mailer are always installed (before django.contrib.admin, for migration order),
as are the health and commands API. Optional apps (currency, geo, analytics, chat, payments, RQ)
are added by the apps builder when you set the matching config section; there is no enable_* flag per app.
5. Modules (django_cfg/modules/)
Feature modules for common integrations:
from django_cfg import DjangoEmailService, send_telegram_message
send_telegram_message("Deploy finished", chat_id="123456789")django_email- email service (DjangoEmailService,send_email)django_telegram- Telegram (DjangoTelegram,send_telegram_message,send_telegram_photo)django_logging- the generatedLOGGINGdict, smart collapsing handler, log pruningdjango_rq- Django-RQ integrationdjango_admin,admin_site-PydanticAdminand the admin site (stock Django admin, navigation, theme)django_llm,django_mcp,django_notion,django_currency,django_health,django_import_export,django_generator,django_monitor,django_sitemap,django_cleanup,django_migrator,django_tailwind,django_drf_theme,django_dashboard
6. Management commands (django_cfg/management/commands/)
Examples: migrator, migrate_all, show_config, check_settings, check_endpoints,
show_urls, list_urls, pool_status, log_prune, log_noise, test_email,
test_telegram, telegram_bot, superuser, generate_fastapi, mcp_install, mcp_doctor.
RQ workers run through manage.py rqworker (see Django-RQ).
7. CLI (django_cfg/cli/)
The django-cfg command: create-project and info (see CLI Tools).
System Architecture Diagram
Component Interaction Flow
1. Configuration loading
class MyConfig(DjangoConfig):
project_name: str = "My App"
jwt: JWTConfig = JWTConfig() # an optional section: its app is added when set
config = MyConfig() # validates with Pydantic
settings = config.get_all_settings() # generates Django settings2. Django integration
# settings.py - single-line integration
from .config import config
globals().update(config.get_all_settings())The generated dict contains INSTALLED_APPS (WhiteNoise and import-export, the django-cfg admin app CfgAdminConfig in place of django.contrib.admin, then Django, third-party and django-cfg apps),
DATABASES, MIDDLEWARE, TEMPLATES, CACHES, LOGGING, REST_FRAMEWORK and the security settings.
See Django Integration.
Security Architecture
- Environment variables: secrets come from the environment; see Environment Variables
- Type validation: Pydantic rejects wrong types and unknown fields
- Secure defaults: the security builder generates cookie, HSTS and SSL settings from your config (see Security Settings)
- CORS and CSRF: typed settings, see CORS
- Authentication: OTP, OAuth and optional two-factor through
apps/system/accountsandapps/system/totp - Rate limiting: see Rate Limiting
Extension Points
Custom configuration sections
DjangoConfig forbids unknown fields, so a subclass must declare every extra setting as a typed field.
Group related settings in a plain Pydantic model:
import os
from pydantic import BaseModel, Field
from django_cfg import DjangoConfig
class MyServiceConfig(BaseModel):
api_key: str = Field(default_factory=lambda: os.environ.get("MY_SERVICE_API_KEY", ""))
timeout: int = Field(30, description="Request timeout")
class MyConfig(DjangoConfig):
my_service: MyServiceConfig = Field(default_factory=MyServiceConfig)Import Contracts and Public API
Layering is checked by import-linter (config in [tool.importlinter] of django-cfg’s pyproject.toml):
cd projects/django-cfg
make lint-imports # report-only, never part of `make test`| Contract | Rule |
|---|---|
django_cfg layers | cli/management > apps > modules > middleware/mixins/templatetags > core > models > utils: a layer imports only downward |
feature modules are independent | django_llm, django_generator, django_mcp, django_admin, django_rq, django_notion, django_monitor, django_sitemap, django_cleanup do not import each other |
product apps are independent | apps.tools.geo, apps.tools.currency, apps.tools.analytics do not import each other |
core and models do not import features | core and models never import apps or modules |
core and models stay light | core and models do not import openai, pydantic_ai, tiktoken, PIL, cv2, telebot, boto3, stripe, jinja2 |
optional extras are confined | apps, core, models, middleware do not import stripe, boto3, pglast, pydantic_ai, openai |
The check is report-only: today’s known violations are listed per contract in ignore_imports as a baseline. The list shrinks, it does not grow; a new entry needs a reason in review. The target is to make it fail the build after the baseline is cleared.
Two tests guard what consumers rely on:
tests/test_public_api.pycomparesdjango_cfg.__all__and everydjango_cfg.*module path that the active projects import againsttests/public_api_snapshot.json. A removed name or path fails the test; regenerate thealllist withUPDATE_PUBLIC_API_SNAPSHOT=1 pytest tests/test_public_api.pyonly as a visible review decision. This is whyfrom django_cfg import Iconskeeps working while its implementation moved todjango_cfg.icons.tests/test_import_budget.pymeasuresimport django_cfgin a clean subprocess: a ceiling on the number ofdjango_cfgmodules loaded, and a list of heavy packages (openai,boto3,pandas, …) that must stay unloaded. The budget is lowered when the facade gets lazier and never raised without a reason.
Call-site rules are enforced by ruff: T201 (no print) and G004 (no f-string in a logging call) apply to new library code; existing debt is listed per path in pyproject.toml. See Django Logging.
See Also
Architecture & Internals
Configuration:
- Configuration - Complete configuration API reference
- Type-Safe Configuration - Pydantic validation patterns
- Environment Detection - Multi-environment configuration
Django Integration
Framework Integration:
- Django Integration - How Django-CFG integrates with Django
- Security Settings - CORS, CSRF, SSL configuration
- Database Configuration - Database setup
- Cache Configuration - Redis and caching patterns
Getting Started
Quick Start:
- Installation - Install Django-CFG
- First Project - Create your first project
- Configuration Guide - Environment-based configuration setup
Features:
- Built-in Apps - Production-ready applications
- Modules Overview - Reusable modules system
- Integrations Overview - Third-party integrations
Tools & Deployment
Development:
- CLI Tools - Command-line interface
- Troubleshooting - Common issues and solutions
Production:
- Production Config - Production deployment guide
- Docker Deployment - Containerized deployment