Startup & Validation
Django-CFG runs a set of focused startup hooks from AppConfig.ready() that validate the registry, patch DRF authentication, install development type stubs, and register Constance admin. It also provides a rich startup information display to show system status at a glance.
Startup Validation Hooks
These hooks run automatically from DjangoCfgConfig.ready(). They are each isolated in their own module under django_cfg/startup/.
Registry Validation (registry_validation.py)
validate_registry() walks every entry in DJANGO_CFG_REGISTRY and confirms that the module can be imported and the expected attribute exists on it.
- Optional-dependency entries (gRPC, Centrifugo, ngrok, import-export, Unfold, Cloudflare) that fail with
ImportErrorare logged atDEBUGlevel only — these failures are expected when the optional package is not installed. - Required entries that fail (missing attribute or unexpected error) are logged as
ERRORand collected into a summary warning. - The check is read-only and idempotent — calling it multiple times is safe.
# Logger: django_cfg.registry
# Level: DEBUG for optional deps, ERROR for required depsThis surfaces broken registry entries at startup rather than deferring the failure until the first request in production.
DRF Authentication Patch (drf_patch.py)
patch_drf_authentication() re-applies the JWT-aware DRF Request._authenticate monkey-patch after all apps are loaded.
The patch ensures that AuthenticationFailed raised by non-JWT backends does not block JWT authentication when the request carries a JWT Bearer token. This allows projects to register API-key or other custom authentication backends alongside JWTAuthenticationWithLastLogin without modifying those backends.
The patch is idempotent — applying it twice replaces the method with the same implementation.
See ./middleware for full details on the JWT authentication class.
Type Stubs (type_stubs.py)
install_type_stubs() runs only in development environments (DJANGO_ENV != "production").
It writes typings/rest_framework/serializers.pyi and patches pyrightconfig.json so that Pyright narrows serializer.validated_data to dict[str, Any] after is_valid(raise_exception=True) is called. This eliminates a common Pyright false-positive in DRF views.
The hook is a no-op in production and silently swallows all exceptions to avoid breaking the server start.
Constance Admin Registration (constance.py)
register_constance_admin() registers the Constance Config model in the Django admin using an Unfold-styled ModelAdmin when both django-constance and django-unfold are installed.
- No-op if
CONSTANCE_CONFIGis empty or either package is missing. - Ensures the Constance settings page respects the Unfold admin theme without requiring manual
admin.pyconfiguration in the project.
Startup Information Display
Django-CFG provides a comprehensive startup information system that gives you complete visibility into your application’s configuration, status, and available features when your Django server starts.
Overview
The startup information system displays:
- System Configuration: Version, environment, project details
- Application Status: Enabled apps, endpoints, and integrations
- Dynamic Settings: Constance fields from multiple sources
- Development Tools: Management commands, background tasks
- Health Monitoring: Service status and update notifications
Display Modes
Control the verbosity of startup information with three configurable modes:
🔴 NONE Mode
Perfect for: Production, CI/CD, Docker containers
Django CFG v1.2.30 • production • My Project • 🚨 UPDATE AVAILABLEFeatures:
- Single line output
- Critical information only
- Update notifications
- Minimal resource usage
🟡 SHORT Mode
Perfect for: Development, staging, quick checks
Shows:
- Compact header with version and environment
- Apps grid (up to 8 apps)
- Essential endpoints (up to 6)
- System status metrics
- Update notifications
- Commands summary
Layout: Horizontal columns, space-efficient
🟢 FULL Mode (Default)
Perfect for: Development, debugging, system analysis
Shows comprehensive system overview:
Main Information Panels
- Django CFG Configuration: Version, environment, project info, health endpoint
- Update Notifications: Version comparison and upgrade instructions
- Background Tasks: ReArq status, queue configuration, worker commands
- Management Commands: Complete breakdown of available CLI tools
Dynamic Configuration
- Constance Fields Summary: Runtime settings breakdown by source
- User-defined fields
- Tasks module fields
- Knowbase app fields
- Payments app fields
- Total field count
Application Overview
- Enabled Apps & Endpoints: Side-by-side view of active applications and their API endpoints
- App-Specific Status: Payment systems, task queues, knowledge base
- System Configuration: Cache, validation, installed apps count
Detailed Breakdowns
- Core & App Commands: Django-CFG commands alongside app-specific tools
- Project Commands: Local management commands in organized columns
- Settings Details: Constance field details grouped by category (General, Blog, etc.)
Configuration
In your DjangoConfig:
from django_cfg.core.config import DjangoConfig, StartupInfoMode
class MyProjectConfig(DjangoConfig):
project_name: str = "My Project"
# Control startup information display
startup_info_mode: StartupInfoMode = StartupInfoMode.FULL # DefaultEnvironment Variables:
# Control via environment variable
DJANGO_STARTUP_INFO_MODE=none # Minimal
DJANGO_STARTUP_INFO_MODE=short # Essential
DJANGO_STARTUP_INFO_MODE=full # Complete (default)Environment-Based Configuration:
import os
from django_cfg.core.config import StartupInfoMode
class MyProjectConfig(DjangoConfig):
startup_info_mode: StartupInfoMode = (
StartupInfoMode.NONE if os.getenv('DJANGO_ENV') == 'production'
else StartupInfoMode.FULL
)Key Features
Rich Visual Layout
- Consistent Width: All panels use standardized 120-character width
- Balanced Columns: Perfect 50/50 split for two-column layouts
- Integrated Blocks: Complex information organized in nested components
- Color Coding: Different colors for different types of information
Smart Information Discovery
- Dynamic App Detection: Automatically discovers enabled Django-CFG apps
- Constance Integration: Collects runtime settings from all sources
- Command Collection: Finds and categorizes all available management commands
- Version Monitoring: Checks for updates with intelligent caching
Performance Optimized
- Lazy Loading: Information gathered only when needed
- Caching: Version checks cached to prevent redundant API calls
- Error Resilience: Graceful degradation when services unavailable
- Resource Efficient: Mode-based resource usage
What You’ll See
System Information
🚧 Django CFG Configuration
Version: 1.2.30
🌍 Environment: development
🏗️ Project: My Django Project
❤️ Health: http://localhost:8000/cfg/health/Application Status
📱 Enabled Apps 🔗 Endpoints
• health • http://localhost:8000/cfg/health/
• commands • http://localhost:8000/cfg/commands/
• payments • http://localhost:8000/api/payments/
• knowbase • http://localhost:8000/api/knowbase/Dynamic Configuration
📊 Constance Fields Summary
User Defined 5
Payments App 4
Knowbase App 3
Total 12
General Settings Blog Settings
SITE_NAME str MAX_POSTS_PER_PAGE int
SITE_DESCRIPTION str FEATURED_POSTS bool
MAINTENANCE_MODE boolDevelopment Tools
Management Commands
Core Commands 21
📱 App Commands 11
🏗️ Project Commands 58
📊 Total 90Benefits
For Developers
- Instant Overview: See your entire application status at a glance
- Configuration Validation: Spot misconfigurations immediately
- Feature Discovery: Find available commands and endpoints
- Debug Information: Rich context for troubleshooting
For Teams
- Consistent Experience: Same information display across environments
- Documentation: Self-documenting application structure
- Onboarding: New team members understand the system quickly
- Monitoring: Easy to spot when services are down or misconfigured
For Operations
- Health Monitoring: Immediate visibility into system status
- Version Management: Clear update notifications
- Environment Validation: Confirm correct environment configuration
- Resource Optimization: Choose appropriate verbosity for each environment
Troubleshooting
Common Scenarios
Missing Information: If expected apps or endpoints don’t appear, check:
- App is properly installed in
INSTALLED_APPS - App configuration is enabled in your DjangoConfig
- No errors in app initialization
Performance Issues: If startup feels slow:
- Use
SHORTorNONEmode for faster startup - Check for network issues affecting version checking
- Review app initialization code for bottlenecks
Layout Problems: If information appears misaligned:
- Ensure terminal width is at least 120 characters
- Check for special characters in app names or descriptions
- Verify Rich library is properly installed
Best Practices
Development Workflow
# During active development - see everything
startup_info_mode = StartupInfoMode.FULL
# For quick testing - essential info only
startup_info_mode = StartupInfoMode.SHORT
# For production - minimal noise
startup_info_mode = StartupInfoMode.NONEEnvironment Configuration
# Automatic mode selection based on environment
class ProductionConfig(DjangoConfig):
startup_info_mode: StartupInfoMode = StartupInfoMode.NONE
class DevelopmentConfig(DjangoConfig):
startup_info_mode: StartupInfoMode = StartupInfoMode.FULL
class StagingConfig(DjangoConfig):
startup_info_mode: StartupInfoMode = StartupInfoMode.SHORTCI/CD Integration
# In your deployment scripts
export DJANGO_STARTUP_INFO_MODE=none
# In your development docker-compose
environment:
- DJANGO_STARTUP_INFO_MODE=short🔮 Advanced Features
AI Development Hints
Django-CFG displays helpful hints for AI assistants (Claude, GPT, Cursor, etc.) in the startup output. These hints help AI tools understand Django 5.2+ async patterns and best practices.
Example output (FULL mode):
┌──────────────────────────────────────────────────────────────────┐
│ 🤖 AI Development Hints (Django 5.2+) │
├──────────────────────────────────────────────────────────────────┤
│ ━━ ASYNC ━━ │
│ ● Django 5.2 Async ORM Use a-prefixed methods: aget(), │
│ acreate(), aupdate(), adelete() │
│ ● Async QuerySet... Use 'async for' for iteration │
│ ━━ TYPING ━━ │
│ ● Pydantic for RPC Use Pydantic models instead of │
│ Optional[dict] for handler params │
└──────────────────────────────────────────────────────────────────┘Configuration:
from django_cfg.core.config import DjangoConfig
class MyProjectConfig(DjangoConfig):
project_name: str = "My Project"
# Enable/disable AI hints (default: True)
show_ai_hints: bool = TrueEnvironment variable:
DJANGO_SHOW_AI_HINTS=false # Disable AI hintsIncluded hints:
- Django 5.2 Async ORM: Use
aget(),acreate(),aupdate(),adelete()methods - Async QuerySet Iteration: Use
async forinstead of list comprehensions - Sync to Async: Use
sync_to_async()wrapper for sync functions - Pydantic for RPC: Use Pydantic models for type-safe API params
Ngrok Integration
When using ngrok for local development, the system automatically detects and displays:
- Tunnel status and configuration
- Public URL for webhook testing
- Usage instructions
Update Monitoring
- Automatic checking for new Django-CFG versions
- Prominent display when updates are available
- Direct upgrade commands provided
Background Tasks
- ReArq queue status and configuration
- Worker startup commands
- Task-related management commands
The startup information system is designed to be your mission control center - giving you complete visibility and control over your Django-CFG application from the moment it starts.