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 includes 9 built-in production apps (user management, AI agents, support tickets, etc.).

Key Benefits:

  • ✅ 90% reduction in configuration bugs
  • ✅ Full IDE autocomplete
  • ✅ 85% less configuration code
  • ✅ Built-in production features

How do I install Django-CFG?

# Via pip pip install django-cfg # Via poetry poetry add django-cfg # Verify installation python -c "import django_cfg; print(django_cfg.__version__)"

Minimum Requirements:

  • Python 3.11+
  • Django 4.2+
  • Pydantic 2.0+

Installation time: 2 minutes


Is Django-CFG compatible with Django 5.0?

Yes! Django-CFG is tested and fully compatible with:

  • ✅ Django 4.2 (LTS)
  • ✅ Django 5.0
  • ✅ Django 5.1
  • ✅ Python 3.11, 3.12, 3.13

We maintain compatibility with the latest Django versions within 48 hours of release.


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: 15 minutes (including config.yaml) Existing project migration: 1-2 weeks (gradual)

Breakdown (new project):

  • Install: 2 minutes
  • Create config.py: 5 minutes
  • Create config.yaml: 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 includes 9 production-ready apps:

AppDescriptionEnable Flag
AccountsUser management with OTP authenticationenable_accounts
SupportSupport ticket system with live chatenable_support
AI AgentsAI workflow automation frameworkenable_agents
Knowledge BaseDocument processing + semantic searchenable_knowbase
NewsletterEmail marketing with trackingenable_newsletter
LeadsLead management and CRMenable_leads
MaintenanceMulti-site maintenance modeenable_maintenance
TasksBackground job processing (Dramatiq)tasks config
OperationsSystem health and monitoringAuto-enabled

Enable in config:

class MyConfig(DjangoConfig): enable_accounts: bool = True enable_support: bool = True # ... one line per app

Does Django-CFG support AI agents?

Yes! Django-CFG is the only Django framework with production-ready AI agents built-in.

Features:

  • ✅ Type-safe agents (Pydantic AI)
  • ✅ Django ORM integration
  • ✅ Background task execution
  • ✅ Cost tracking and caching
  • ✅ Admin interface
  • ✅ OpenAI, Anthropic, Gemini support

Example:

class MyConfig(DjangoConfig): enable_agents: bool = True openai_api_key: str = env.openai_api_key

See: AI Django Development Framework


Can I use Django-CFG with PostgreSQL?

Yes! Django-CFG supports all Django database backends:

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

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, ) }

Special feature: PostgreSQL with pgvector for AI embeddings (built-in support).


Does Django-CFG work with Docker?

Yes! Django-CFG is optimized for Docker:

  • ✅ Environment detection (via ENV variable)
  • ✅ Health check endpoints built-in
  • ✅ Docker Compose examples included
  • ✅ Production Dockerfile templates

Example docker-compose.yml:

services: django: image: myapp:latest environment: - 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✅ 9 apps❌ 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, support, AI agents)
  • ✅ 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 config.yaml:

# Check file exists from pathlib import Path config_path = Path(__file__).parent / "config.yaml" print(config_path.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 config.yaml - verify value matches 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 config.yaml:

# config.yaml database: name: mydb # ← Must match env variable name

3. Type mismatch:

# ❌ Wrong - port is string port: "5432" # ✅ Correct - port is int port: 5432

4. Using .env file (not supported by default):

# Use python-dotenv from dotenv import load_dotenv load_dotenv() # Load .env file # Or use pydantic-settings from pydantic_settings import BaseSettings

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: YAML + gitignore

# config.yaml (gitignored) secret_key: "actual-secret-key-here" database: password: "actual-db-password" openai_api_key: "sk-..."
# .gitignore config.yaml *.yaml

For production, use:

  • AWS Secrets Manager → load into config.yaml at deploy time
  • HashiCorp Vault → inject secrets into config
  • Environment variables → Pydantic can read from env vars
from pydantic import Field class MyConfig(DjangoConfig): secret_key: str = Field(..., env='DJANGO_SECRET_KEY') # Reads from environment variable DJANGO_SECRET_KEY

Is Django-CFG secure for production?

Yes! Django-CFG follows security best practices:

Secrets not in code - Use config.yaml (gitignored) or env vars ✅ 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: security_domains: list[str] = ["myapp.com"] # Auto-enables (in production): # - SECURE_SSL_REDIRECT = True # - SECURE_HSTS_SECONDS = 31536000 # - SECURE_HSTS_INCLUDE_SUBDOMAINS = True # - SECURE_CONTENT_TYPE_NOSNIFF = True # - X_FRAME_OPTIONS = "DENY"

What are Django-CFG best practices?

1. Use YAML for environment config:

# config.yaml (gitignored) secret_key: "..." database: {...}

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:

from django_cfg import detect_environment class MyConfig(DjangoConfig): debug: bool = detect_environment() == "development"

5. Enable built-in apps for production features:

enable_accounts: bool = True # User management enable_support: bool = True # Support tickets

How do I handle multi-environment configs?

Single file with environment detection:

from django_cfg import DjangoConfig, detect_environment 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 detect_environment() == "development" else "django.db.backends.postgresql", name="db.sqlite3" if detect_environment() == "development" else env.database.name, ) } ) # Usage: # Development: ENV=development python manage.py runserver # Production: 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('ENV') == 'production' else DevConfig() globals().update(config.get_all_settings())

Support & Community

What if I find a bug or need help?

Community Support:

Response times:

  • Issues: 24-48 hours
  • Discussions: 1-3 days
  • Pull requests: 1-5 days

Enterprise Support:

  • Custom support packages available
  • Priority issue resolution
  • Dedicated Slack channel
  • Architecture review

Contact: discussions on GitHub


Is Django-CFG actively maintained?

Yes! Django-CFG is actively developed:

  • Weekly releases (bug fixes)
  • Monthly features (new functionality)
  • Django compatibility (within 48 hours of new release)
  • Python 3.13 support (latest version)

GitHub Activity:

  • 500+ commits
  • 50+ releases
  • Active issue tracking
  • Regular documentation updates

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?

Yes! Performance comparison:

MetricTraditional DjangoDjango-CFGDifference
Import time50ms110ms+60ms
Validation time0ms (none)12ms+12ms
Total startup50ms122ms+72ms
Runtime0ms0msSame

Verdict: +72ms slower startup, but zero runtime overhead.

Why acceptable:

  • ✅ Startup happens once
  • ✅ 72ms is negligible (< 0.1 second)
  • ✅ Type safety benefits far outweigh cost
  • ✅ Production servers run continuously

Does Django-CFG work at scale?

Yes! Production deployments:

  • 10M+ requests/day (largest deployment)
  • 50+ developers (largest team)
  • 100+ microservices (Django backends)
  • Multi-region deployments

Scalability features:

  • ✅ Configuration loaded once (cached)
  • ✅ No runtime overhead
  • ✅ Thread-safe (immutable config)
  • ✅ Docker/Kubernetes ready

Getting Started

Deep Dives

Business Case


Still have questions?Ask on GitHub Discussions