Skip to Content
CoreBuilder Pattern

Builder Pattern in Django-CFG

The Builder Pattern is a core architectural pattern in Django-CFG that separates the construction of complex configuration objects from their representation.

Overview

Django-CFG uses dedicated builder classes to construct different parts of Django settings from configuration models. This approach provides:

  • Single Responsibility: Each builder focuses on one aspect of settings
  • Testability: Builders can be tested independently
  • Extensibility: Easy to add custom builders
  • Maintainability: Changes isolated to specific builders

Core Builders

InstalledAppsBuilder

Builds the INSTALLED_APPS list from your DjangoConfig.

Location: django_cfg.core.builders.apps_builder

Responsibilities:

  • Combine default Django apps with third-party apps
  • Add django-cfg apps based on which config sections are enabled (currency, geo, payments, django_rq, mcp, notion, …)
  • Handle special ordering requirements
  • Add auto-discovered extension apps and project_apps
  • Remove duplicates while preserving order

Example:

from django_cfg.core.builders import InstalledAppsBuilder # Inside ConfigService builder = InstalledAppsBuilder(config) apps = builder.build()

Key Features:

  1. Accounts Before Admin: Inserts django_cfg.apps.system.accounts (plus totp and mailer) before django.contrib.admin for proper migration order

  2. RQ Ordering: When django_rq is enabled, django_cfg.modules.django_rq is added before django_rq so django-cfg’s rqcron and rqworker commands win over django-rq’s

MiddlewareBuilder

Builds the MIDDLEWARE list from your DjangoConfig.

Location: django_cfg.core.builders.middleware_builder

Responsibilities:

  • Start with Django’s default middleware stack
  • Insert CORS middleware at correct position
  • Add feature-specific middleware
  • Add custom_middleware from your config
  • Maintain proper ordering

Example:

from django_cfg.core.builders import MiddlewareBuilder builder = MiddlewareBuilder(config) middleware = builder.build()

Key Features:

  1. Smart CORS Insertion: Places the CORS middleware after WhiteNoise but before Session, in a fixed order (see CORS)

    [ "whitenoise.middleware.WhiteNoiseMiddleware", "django_cfg.core.middleware.PublicAPICORSMiddleware", "django_cfg.core.middleware.CorsRequestHeadersMiddleware", "corsheaders.middleware.CorsMiddleware", # ← Inserted here "django.contrib.sessions.middleware.SessionMiddleware", ... ]
  2. Feature Middleware: Automatically adds middleware for enabled features

    • TimezoneMiddleware, ClientIdMiddleware and UserActivityMiddleware always (each listed once)
    • RequestIdMiddleware right after the real-IP middleware, so every log line carries the request id
    • SiteMiddleware only with more than one entry in sites; simple_history middleware only when simple_history is enabled

SecurityBuilder

Builds security-related settings like ALLOWED_HOSTS.

Location: django_cfg.core.builders.security_builder

Responsibilities:

  • Generate ALLOWED_HOSTS, CSRF and CORS settings from security_domains and sites
  • Add localhost in development
  • Add internal service hostnames when running in Docker

Example:

from django_cfg.core.builders import SecurityBuilder builder = SecurityBuilder(config) security_settings = builder.build_security_settings() # ALLOWED_HOSTS, CSRF, CORS, ... allowed_hosts = security_settings["ALLOWED_HOSTS"]

Key Features:

  1. Environment-Aware Defaults:

    # Development security_domains = [] → ALLOWED_HOSTS = ["localhost", "127.0.0.1", "[::1]"] # Production with domains security_domains = ["example.com"] → ALLOWED_HOSTS = ["example.com", "www.example.com"]
  2. Production Warning: Issues warning if no domains configured in production

Usage Pattern

Direct Usage

from django_cfg import DjangoConfig from django_cfg.core.builders import InstalledAppsBuilder config = DjangoConfig(project_name="MyProject", ...) builder = InstalledAppsBuilder(config) apps = builder.build()

Through DjangoConfig

The recommended approach is the DjangoConfig accessors:

from django_cfg import DjangoConfig config = DjangoConfig(project_name="MyProject", ...) # DjangoConfig uses the builders apps = config.get_installed_apps() # Uses InstalledAppsBuilder internally middleware = config.get_middleware() # Uses MiddlewareBuilder internally hosts = config.get_allowed_hosts() # Uses SecurityBuilder internally

Creating Custom Builders

You can create custom builders for your own configuration needs:

from typing import List, TYPE_CHECKING if TYPE_CHECKING: from django_cfg.core.base.config_model import DjangoConfig class CustomSettingsBuilder: """Build custom settings from config.""" def __init__(self, config: "DjangoConfig"): self.config = config def build(self) -> dict: """Build custom settings.""" settings = {} # Your custom logic here if self.config.is_production: settings["CUSTOM_FEATURE"] = True return settings

Integration with Generators

Builders feed into generators:

Example:

# Builder creates INSTALLED_APPS list apps_builder = InstalledAppsBuilder(config) installed_apps = apps_builder.build() # Generator uses the list in settings settings = { "INSTALLED_APPS": installed_apps, ... }

Testing Builders

Builders are designed to be easily testable:

import pytest from django_cfg import DjangoConfig from django_cfg.core.builders import InstalledAppsBuilder def make_config(**kwargs): return DjangoConfig(project_name="Test", secret_key="x" * 50, **kwargs) def test_accounts_before_admin(): apps = InstalledAppsBuilder(make_config()).build() accounts_index = apps.index("django_cfg.apps.system.accounts") admin_index = apps.index("django.contrib.admin") assert accounts_index < admin_index, "Accounts must come before admin" def test_geo_app_only_when_enabled(): from django_cfg import GeoConfig assert "django_cfg.apps.tools.geo" not in InstalledAppsBuilder(make_config()).build() apps = InstalledAppsBuilder(make_config(geo=GeoConfig(enabled=True))).build() assert "django_cfg.apps.tools.geo" in apps

Best Practices

1. Single Responsibility

Each builder should focus on one aspect of configuration:

  • InstalledAppsBuilder - only builds apps list
  • MiddlewareBuilder - only builds middleware list
  • Do not mix concerns

2. Immutability

Builders should not modify the config:

# Good - read from config if self.config.geo and self.config.geo.enabled: apps.append("django_cfg.apps.tools.geo") # Bad - don't modify config self.config.geo.enabled = True

3. Deterministic Output

Same config should always produce same output:

# Good - deterministic apps = ["app1", "app2", "app3"] # Bad - random or time-dependent import random apps = random.sample(all_apps, 5)

4. Error Handling

Provide clear error messages:

if not self.config.databases: raise ConfigurationError( "At least one database must be configured", suggestions=["Add a 'default' database"], )

Comparison with Other Patterns

Builder vs Factory

Builder Pattern (Django-CFG):

  • Constructs complex objects step-by-step
  • Same builder can create different representations
  • Focuses on HOW to build

Factory Pattern:

  • Creates objects in one step
  • Different factories for different types
  • Focuses on WHAT to build

Builder vs Template Method

Builder (Django-CFG):

  • Multiple classes for different aspects
  • Composition over inheritance
  • More flexible

Template Method:

  • Single class with hooks
  • Inheritance-based
  • More rigid structure

See Also

Last updated on