Skip to Content

Django-CFG FAQ - Frequently Asked Questions

Complete answers to the most common questions about Django-CFG, organized by category. Each answer is concise and actionable.


Installation & Setup

What is Django-CFG?

Django-CFG is a type-safe configuration framework for Django that replaces traditional settings.py with Pydantic v2 models. It validates configuration at startup, provides IDE autocomplete, and ships built-in apps for accounts and two-factor sign-in, mail, payments, currency, geo, analytics and chat, plus an LLM client and an MCP server.

Key Benefits:

  • Errors caught at startup, not in production
  • Full IDE autocomplete
  • Much less configuration code than a hand-written settings.py
  • Built-in production features

How do I install Django-CFG?

# Create virtual environment (Python 3.12+ required) python3.12 -m venv .venv && source .venv/bin/activate # Install via pip pip3 install 'django-cfg[full]' # Or via poetry poetry add 'django-cfg[full]' # Verify installation python -c "import django_cfg; print(django_cfg.__version__)"

Minimum Requirements:

  • Python 3.12 or 3.13
  • Django 5.2+
  • Pydantic 2.0+

Installation time: 2 minutes


Which Django and Python versions are supported?

Django 5.2 LTS, 6.0 and 6.1 (>=5.2.14,<6.2) and Python 3.12 or 3.13. Django is a base dependency of django-cfg, so pip install django-cfg installs a supported version. On Django 6.1, email is emitted as MAILERS: see Email.


Do I need to change my existing Django project?

Gradual migration is supported. You can:

  1. Start with minimal config (core settings only)
  2. Keep existing settings.py alongside Django-CFG
  3. Migrate incrementally over weeks/months
  4. No downtime required

Migration time: 1-2 weeks for typical project

See: Migration Guide


How long does setup take?

New project: about 15 minutes (including the .env file) Existing project migration: 1-2 weeks (gradual)

Breakdown (new project):

  • Install: 2 minutes
  • Create config.py: 5 minutes
  • Create the .env file: 3 minutes
  • Test: 2 minutes
  • Run migrations: 3 minutes

Total: 15 minutes to production-ready configuration


Features & Capabilities

What are Django-CFG built-in apps?

Django-CFG ships these apps. There is no enable_* flag per app: some are always installed, the rest switch on when you set their config section.

AppDescriptionSwitched on by
AccountsCustom user model, OTP and OAuth sign-inAlways installed
TOTPTwo-factor authenticationAlways installed
MailerMail delivery, per-locale letter copy, send logAlways installed
Health and commands API/healthz probes, /cfg/commands/Always installed
CurrencyExchange ratescurrency=CurrencyConfig(...)
GeoCountries, states, citiesgeo=GeoConfig(...)
AnalyticsPageview and session ingestanalytics=AnalyticsConfig(...)
ChatAssistant chat threadschat=ChatConfig(...)
PaymentsCheckout, webhooks, refundspayments=PaymentsConfig(...)
Django-RQBackground jobsdjango_rq=DjangoRQConfig(...)

Business apps such as leads or newsletter ship as extensions, not as built-in apps.

Enable in config:

from django_cfg import DjangoConfig, GeoConfig, CurrencyConfig class MyConfig(DjangoConfig): geo: GeoConfig = GeoConfig() currency: CurrencyConfig = CurrencyConfig()

Does Django-CFG support AI and LLMs?

Yes. The django_llm module is a multi-provider LLM client with response caching and cost tracking, and the django_mcp module exposes a Model Context Protocol server so AI agents can use your Django project.

from django_cfg.modules.django_llm import LLMClient

See Django LLM and Django MCP.


Can I use Django-CFG with PostgreSQL?

Yes! DatabaseConfig builds the entry for PostgreSQL, MySQL/MariaDB and SQLite:

  • PostgreSQL (recommended for production)
  • MySQL / MariaDB
  • SQLite (development)

Example:

from django_cfg import DjangoConfig, DatabaseConfig class MyConfig(DjangoConfig): databases: dict[str, DatabaseConfig] = { "default": DatabaseConfig( engine="django.db.backends.postgresql", name=env.database.name, host=env.database.host, port=5432, ) }

Or from a URL: DatabaseConfig.from_url("postgresql://user:pass@host:5432/db").


Does Django-CFG work with Docker?

Yes! Django-CFG is optimized for Docker:

  • Environment detection (via the DJANGO_ENV variable; production is the default)
  • Health check endpoints built in (/healthz/live, /healthz/ready)
  • Docker Compose examples in the docs
  • Production Dockerfile templates

Example docker-compose.yml:

services: django: image: myapp:latest environment: - DJANGO_ENV=production - SECRET_KEY=${SECRET_KEY} # Django-CFG auto-detects production mode

See: Docker Production Setup


What is type-safe configuration?

Type-safe configuration means your configuration values are validated against specific types (int, str, bool, etc.) at startup using Pydantic v2 models.

Example:

# ❌ Not type-safe (traditional Django) DEBUG = os.environ.get('DEBUG', 'False') == 'True' # No validation, returns None if missing # ✅ Type-safe (Django-CFG) debug: bool = False # Pydantic validates boolean conversion at startup # Raises ValidationError if invalid

Benefits:

  • ✅ Errors caught at startup (not in production)
  • ✅ IDE autocomplete works
  • ✅ mypy/pyright can verify types
  • ✅ Clear error messages

Comparison & Migration

Django-CFG vs django-environ: which is better?

Use Django-CFG when:

  • ✅ Production application
  • ✅ Type safety is critical
  • ✅ Complex configuration
  • ✅ Want built-in apps

Use django-environ when:

  • ✅ Simple project (< 10 config values)
  • ✅ Quick prototype
  • ✅ Team doesn’t use type hints
FeatureDjango-CFGdjango-environ
Type Safety✅ Pydantic v2❌ Runtime casting
IDE Autocomplete✅ Full❌ None
Built-in Apps✅ Accounts, mail, payments, …❌ None
Lines of Code30-50150-200

See: Complete Comparison


Can I migrate gradually from settings.py?

Yes! Django-CFG supports gradual migration:

Step 1: Install Django-CFG alongside existing settings.py

# settings.py from django_cfg import DjangoConfig # Start with minimal config class MyConfig(DjangoConfig): secret_key: str = env.secret_key debug: bool = False config = MyConfig() settings_dict = config.get_all_settings() # Keep existing custom settings settings_dict.update({ 'MY_CUSTOM_SETTING': 'value', }) globals().update(settings_dict)

Step 2: Migrate incrementally (database, cache, email, etc.)

Step 3: Remove old settings.py

Timeline: 1-2 weeks for typical project


Is Django-CFG better than pydantic-settings?

Different use cases:

pydantic-settings (generic):

  • ✅ Framework-agnostic (Flask, FastAPI, Django)
  • ❌ No Django-specific features
  • ❌ Manual Django integration

Django-CFG (Django-specific):

  • ✅ Automatic Django settings generation
  • ✅ Built-in apps (accounts, mailer, payments, …)
  • ✅ Django-aware helpers (security_domains, multi-DB routing)

Recommendation:

  • Multi-framework project → pydantic-settings
  • Django-only project → Django-CFG

See: Detailed Comparison


Does Django-CFG replace Django’s settings.py?

Yes and No:

Yes - Django-CFG generates Django settings:

config = MyConfig() globals().update(config.get_all_settings()) # Generates: DATABASES, ALLOWED_HOSTS, MIDDLEWARE, etc.

No - You can keep custom settings alongside:

config = MyConfig() globals().update(config.get_all_settings()) # Add custom settings MY_CUSTOM_SETTING = "value"

Best practice: Migrate core settings to Django-CFG, keep edge cases in settings.py temporarily.


Troubleshooting

Django-CFG configuration not loading - how to fix?

Common causes:

1. Missing .env file or variable:

# Check the file exists from pathlib import Path print((Path(__file__).parent.parent / ".env").exists()) # Should be True

2. Pydantic validation error:

# Run Django check to see detailed error python manage.py check # Output shows exactly what's wrong: # ValidationError: secret_key - Field required

3. Import error:

# Make sure django-cfg is installed pip list | grep django-cfg # Reinstall if needed pip install --upgrade django-cfg

4. Wrong settings module:

# Check DJANGO_SETTINGS_MODULE echo $DJANGO_SETTINGS_MODULE # Should point to file with config.get_all_settings()

How to debug Django-CFG validation errors?

Django-CFG uses Pydantic validation with detailed error messages:

Example error:

ValidationError: 2 validation errors for MyConfig databases.default.port Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='5432extra', input_type=str] secret_key String should have at least 50 characters [type=string_too_short, actual_length=20, min_length=50]

How to fix:

  1. Read error message - shows field name and expected type
  2. Check your .env or environment - verify the value matches the type
  3. Use Field() for validation - add custom validators
from pydantic import Field class MyConfig(DjangoConfig): secret_key: str = Field(..., min_length=50, description="Must be 50+ chars")

Django-CFG Pydantic validation failing?

Debug steps:

1. Check Pydantic version:

pip show pydantic # Required: Pydantic 2.0+

2. Enable debug mode:

# config.py class MyConfig(DjangoConfig): model_config = ConfigDict( validate_default=True, # Validate default values validate_assignment=True, # Validate on assignment )

3. Test config in isolation:

# test_config.py from myproject.config import MyConfig try: config = MyConfig() print("✅ Config valid!") except Exception as e: print(f"❌ Config error: {e}")

Why is my environment variable not working?

Common issues:

1. Environment variable not set:

# Check if variable exists echo $DATABASE_URL # If empty, set it: export DATABASE_URL="postgresql://..."

2. Wrong variable name in your loader:

django-cfg itself reads only a few variables (DJANGO_ENV, ENVIRONMENT, ENV, DJANGO_CFG_BANNER, …). Every other variable is read by your own pydantic-settings loader, so the name must match its fields (DATABASE__NAME for database.name with env_nested_delimiter="__").

3. Type mismatch:

# Wrong: not an integer DATABASE__PORT=five432 # Correct DATABASE__PORT=5432

4. .env file not loaded:

from pydantic_settings import BaseSettings, SettingsConfigDict class Env(BaseSettings): model_config = SettingsConfigDict(env_file=".env")

How do I test different configurations?

Easy with Django-CFG (config is just a class):

# tests/test_config.py from myproject.config import MyConfig from django_cfg import DatabaseConfig def test_development_config(): """Test development configuration""" config = MyConfig( debug=True, databases={ "default": DatabaseConfig( engine="django.db.backends.sqlite3", name=":memory:", ) } ) assert config.debug is True settings = config.get_all_settings() assert settings['DATABASES']['default']['ENGINE'] == "django.db.backends.sqlite3" def test_production_config(): """Test production configuration""" config = MyConfig( debug=False, security_domains=["myapp.com"] ) assert config.debug is False settings = config.get_all_settings() assert "myapp.com" in settings['ALLOWED_HOSTS']

Benefits:

  • ✅ No global state
  • ✅ Easy to instantiate different configs
  • ✅ Clean, readable tests

Security & Best Practices

How do I manage secrets with Django-CFG?

Recommended approach: environment variables, or a gitignored .env file read by your pydantic-settings loader.

# .gitignore .env .env.*
# .env (gitignored) SECRET_KEY=actual-secret-key-here DATABASE__PASSWORD=actual-db-password OPENAI_API_KEY=sk-...

For production, use:

  • AWS Secrets Manager or HashiCorp Vault → inject as environment variables at deploy time
  • Docker / Kubernetes secrets → exported as environment variables
import os from django_cfg import DjangoConfig class MyConfig(DjangoConfig): secret_key: str = os.environ["DJANGO_SECRET_KEY"]

Is Django-CFG secure for production?

Yes! Django-CFG follows security best practices:

✅ Secrets not in code - Use environment variables or a gitignored .env ✅ Validation - Invalid config fails at startup (not in production) ✅ Type safety - No string injection vulnerabilities ✅ Smart defaults - Security headers enabled automatically ✅ SSL/HSTS - Auto-configured in production via security_domains

Security features:

class MyConfig(DjangoConfig): # Auto-generates security settings (ALLOWED_HOSTS, CORS, CSRF origins): security_domains: list[str] = ["myapp.com"]

See Security Settings for the generated SSL, HSTS and cookie settings.


What are Django-CFG best practices?

1. Load environment config with pydantic-settings (.env gitignored):

# .env SECRET_KEY=... DATABASE__NAME=mydb

2. Use Pydantic models for structure:

from pydantic import BaseModel class DatabaseEnv(BaseModel): name: str host: str port: int = 5432

3. Validate required fields:

from pydantic import Field class MyConfig(DjangoConfig): secret_key: str = Field(..., min_length=50) # Required, min 50 chars

4. Use environment detection:

import os class MyConfig(DjangoConfig): debug: bool = os.environ.get("DJANGO_ENV", "development") == "development"

5. Turn on built-in features through config sections:

payments: PaymentsConfig = PaymentsConfig(...) geo: GeoConfig = GeoConfig()

How do I handle multi-environment configs?

Single file with environment detection:

import os from django_cfg import DjangoConfig class MyConfig(DjangoConfig): """Auto-detects environment""" # Different database per environment databases: dict[str, DatabaseConfig] = Field( default_factory=lambda: { "default": DatabaseConfig( # SQLite for dev, PostgreSQL for prod engine="django.db.backends.sqlite3" if os.environ.get("DJANGO_ENV") == "development" else "django.db.backends.postgresql", name="db.sqlite3" if os.environ.get("DJANGO_ENV") == "development" else env.database.name, ) } ) # Usage: # Development: DJANGO_ENV=development python manage.py runserver # Production: DJANGO_ENV=production python manage.py runserver

Or separate config classes:

class BaseConfig(DjangoConfig): """Shared settings""" project_name: str = "My App" class DevConfig(BaseConfig): """Development settings""" debug: bool = True databases: dict[str, DatabaseConfig] = {...} # SQLite class ProdConfig(BaseConfig): """Production settings""" debug: bool = False databases: dict[str, DatabaseConfig] = {...} # PostgreSQL # In settings.py from myproject.config import DevConfig, ProdConfig import os config = ProdConfig() if os.environ.get('DJANGO_ENV') == 'production' else DevConfig() globals().update(config.get_all_settings())

Support & Community

What if I find a bug or need help?

Community Support:

Open an issue or a discussion on GitHub.


Is Django-CFG actively maintained?

Yes! Django-CFG is actively developed:

  • Frequent releases (see Updates)
  • Django 5.2, 6.0 and 6.1, Python 3.12 / 3.13 supported

Roadmap: GitHub Projects 


Can I contribute to Django-CFG?

Yes! Contributions welcome:

Ways to contribute:

  1. Report bugs - GitHub Issues
  2. Suggest features - GitHub Discussions
  3. Submit PRs - Code contributions
  4. Improve docs - Documentation fixes
  5. Share use cases - Case studies

Contribution guide: CONTRIBUTING.md 


Performance & Scalability

Is Django-CFG fast?

Configuration is validated and the settings dict generated once, at process start. There is no per-request overhead from django-cfg’s configuration layer.

import django_cfg is kept light by a budget test (tests/test_import_budget.py: a ceiling on loaded modules and a list of heavy packages that must stay unloaded), and the settings dict is cached on the config instance.


Does Django-CFG work at scale?

Yes. The config is read-only after startup, so it is safe across threads and worker processes, and it works the same under gunicorn, uvicorn/daphne, Docker and Kubernetes.


Getting Started

Deep Dives

Business Case


Still have questions? → Ask on GitHub Discussions 

Last updated on