Skip to Content
CoreArchitecture

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

  1. Type safety: all configuration is Pydantic models (extra="forbid", so a misspelled field fails)
  2. Fail-fast: configuration errors are raised when the config is instantiated, not during requests
  3. Environment-aware: env_mode plus DJANGO_ENV / ENVIRONMENT / ENV select dev, test or production defaults
  4. Lazy facade: import django_cfg stays light; heavy modules load on first use
  5. 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 command

1. 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 dict

DjangoConfig 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.py
  • core/generation/ - generators for databases, cache, email, logging, DRF, RQ, OAuth and the rest of the settings
  • core/environment/ - environment detection
  • core/integration/ - URL integration, startup display, version check
  • core/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 access

A 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, LoggingConfig
  • models/api/ - JWTConfig, DRFConfig, OAuth, LimitsConfig, TwoFactorConfig, CORS and rate limiting
  • models/django/ - RQ, Constance, Currency, Geo, Storage, Payments, Site, OpenAPIClientConfig and similar
  • models/services/ - EmailConfig, TelegramConfig
from django_cfg import DatabaseConfig db = DatabaseConfig.from_url("postgresql://user:pass@localhost:5432/app") db.to_django_config() # Django DATABASES entry

4. Built-in apps (django_cfg/apps/)

PathWhat it provides
apps/system/accountsCustom user model, OTP and OAuth sign-in
apps/system/totpTwo-factor authentication
apps/system/mailerMail delivery and templates
apps/tools/{geo,currency,analytics,chat}Geo data, currency rates, analytics, chat
apps/paymentsPayments
apps/apiHealth 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 generated LOGGING dict, smart collapsing handler, log pruning
  • django_rq - Django-RQ integration
  • django_admin, admin_site - PydanticAdmin and 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 settings

2. 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/accounts and apps/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`
ContractRule
django_cfg layerscli/management > apps > modules > middleware/mixins/templatetags > core > models > utils: a layer imports only downward
feature modules are independentdjango_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 independentapps.tools.geo, apps.tools.currency, apps.tools.analytics do not import each other
core and models do not import featurescore and models never import apps or modules
core and models stay lightcore and models do not import openai, pydantic_ai, tiktoken, PIL, cv2, telebot, boto3, stripe, jinja2
optional extras are confinedapps, 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.py compares django_cfg.__all__ and every django_cfg.* module path that the active projects import against tests/public_api_snapshot.json. A removed name or path fails the test; regenerate the all list with UPDATE_PUBLIC_API_SNAPSHOT=1 pytest tests/test_public_api.py only as a visible review decision. This is why from django_cfg import Icons keeps working while its implementation moved to django_cfg.icons.
  • tests/test_import_budget.py measures import django_cfg in a clean subprocess: a ceiling on the number of django_cfg modules 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:

Django Integration

Framework Integration:

Getting Started

Quick Start:

Features:

Tools & Deployment

Development:

Production:

Last updated on