Skip to Content
FeaturesModulesOverview

Modules System Overview

Django-CFG provides a powerful modular system that automatically configures Django services based on your configuration. Modules eliminate boilerplate code and provide production-ready functionality out of the box.

What are Modules?

Modules are auto-configuring services that:

  • 🔧 Auto-discover configuration from your Django-CFG settings
  • ⚡ Zero-setup integration - just import and use
  • 🛡️ Production-ready with error handling and logging
  • 🔌 Extensible - create your own modules easily
  • 📊 Observable - built-in monitoring and health checks

Architecture

Base Module System

All modules inherit from BaseCfgModule:

from django_cfg.modules.base import BaseCfgModule class MyCustomModule(BaseCfgModule): def __init__(self): super().__init__() self.config = self.get_config() # Auto-discovers Django-CFG config def my_method(self): # Access configuration automatically if hasattr(self.config, 'my_service'): return self.config.my_service.api_key

Configuration Discovery

Modules automatically find your configuration:

# api/config.py class MyProjectConfig(DjangoConfig): email: EmailConfig = EmailConfig( host=env.email.host, port=env.email.port ) # Anywhere in your code from django_cfg import DjangoEmailService email = DjangoEmailService() # Automatically uses your EmailConfig email.send_simple("Test", "Hello!", ["[email protected]"])

Built-in Modules

📧 Communication

Email Module (DjangoEmailService)

Auto-configuring email service with multiple backends:

from django_cfg import DjangoEmailService email = DjangoEmailService() # Simple email email.send_simple( subject="Welcome!", message="Hello World!", recipient_list=["[email protected]"] ) # Template-based email email.send_template( template_name="welcome_email.html", context={"user_name": "John"}, recipient_list=["[email protected]"], subject="Welcome to our platform!" ) # Attachments email.send_with_attachments( subject="Report", message="See attached", recipient_list=["[email protected]"], attachments=[...], )

Features:

  • ✅ Multiple backends (SMTP, etc.)
  • ✅ Template rendering with Django templates
  • ✅ Attachment handling
  • ✅ HTML/text alternatives
  • ✅ Sent on a background thread

Telegram Module (DjangoTelegram)

Bot integration and notifications:

from django_cfg import DjangoTelegram, send_telegram_message telegram = DjangoTelegram() # Send notifications telegram.send_message( chat_id="-1001234567890", message="Deployment completed successfully!" ) # Send with formatting telegram.send_message( chat_id="@my_channel", message="*Error Alert*\n`Database connection failed`", parse_mode="Markdown" ) # Send files telegram.send_document( chat_id="123456789", document=open("report.pdf", "rb"), caption="Monthly report" )

Features: Message sending and formatting, file and photo uploads, a rate-limited queue, and repeat-message dedupe (TelegramConfig.dedupe, 60s window; see Django Telegram).

⚙️ Operations

Health Check Module

Django-CFG provides health check views:

# In your urls.py from django_cfg.modules.django_health import HealthCheckView, SimpleHealthView urlpatterns = [ path('healthz/ready', HealthCheckView.as_view(), name='health-check'), path('healthz', SimpleHealthView.as_view(), name='health-simple'), ]

Built-in Checks:

  • ✅ Database connectivity
  • ✅ Cache availability (Redis/Memcached)
  • ✅ Disk space and memory
  • ✅ Returns JSON health status

Logging Module (django_logging)

django-cfg does not wrap the logger: use logging.getLogger(__name__). The module generates the Django LOGGING dict (stdout by default, opt-in file, text or JSON) and prunes old log files. See Django Logging.

import logging logger = logging.getLogger(__name__) logger.info("User login", extra={"user_id": 123})

Features:

  • ✅ stdout/stderr by default, opt-in log file
  • ✅ JSON off a terminal
  • ✅ Size rotation and boot-time pruning
  • ✅ Monitor events through the same pipeline

Django-RQ Task Queue Module

Type-safe task scheduling with Django-RQ for background job processing:

from django_cfg import DjangoRQConfig, RQQueueConfig, RQScheduleConfig # In config.py django_rq = DjangoRQConfig( enabled=True, redis_db=0, # Required: unique per project (0-15) queues=[ RQQueueConfig(queue="default"), RQQueueConfig(queue="high", default_timeout=3600), ], schedules=[ # Sync data every 5 minutes RQScheduleConfig( func="myapp.tasks.sync_data", interval=300, # seconds queue="default", ), # Daily cleanup at 2 AM RQScheduleConfig( func="myapp.tasks.cleanup_old_data", cron="0 2 * * *", queue="default", ), ], )

Features: High performance (10K+ jobs/sec), cron & interval scheduling, built-in monitoring (Admin, REST API, Prometheus), job dependencies, retry logic, type-safe configuration, and production-ready error handling.

Learn more: Django-RQ Integration Documentation

🚀 Advanced Modules

Currency Module (CurrencyConverter)

Multi-currency support with real-time rates and crypto:

from django_cfg.apps.tools.currency.services.converter import get_converter converter = get_converter() result = converter.convert(100, "USD", "EUR") print(f"{result.result} EUR, rate {result.rate.rate}, source {result.rate.source}")

For model fields (MoneyField) and price formatting see django_cfg.modules.django_currency.


LLM Module (LLMClient)

AI/LLM integration with multiple providers:

from django_cfg.modules.django_llm import LLMClient client = LLMClient() # Chat completion response = client.chat_completion( messages=[ {"role": "system", "content": "You are a helpful Django expert"}, {"role": "user", "content": "How do I optimize Django queries?"} ], model="gpt-4" )

Note: See LLM Module Documentation for complete API reference.

🔌 Creating Custom Modules

Basic Custom Module

from django_cfg.modules.base import BaseCfgModule from typing import Optional class MyCustomService(BaseCfgModule): """Custom service module.""" def __init__(self): super().__init__() self.config = self.get_config() self.my_config = getattr(self.config, 'my_service', None) def do_something(self) -> str: """Perform custom operation.""" if not self.my_config: raise ValueError("MyService not configured") # Use configuration api_key = self.my_config.api_key base_url = self.my_config.base_url # Your service logic here return "Operation completed" def health_check(self) -> dict: """Health check for monitoring.""" try: # Test your service result = self.do_something() return { "status": "healthy", "details": "Service is operational" } except Exception as e: return { "status": "unhealthy", "details": str(e) }

Configuration Integration

# api/config.py from pydantic import BaseModel class MyServiceConfig(BaseModel): api_key: str base_url: str = "https://api.myservice.com" timeout: int = 30 retries: int = 3 class MyProjectConfig(DjangoConfig): my_service: MyServiceConfig = MyServiceConfig( api_key=env.my_service.api_key )

Best Practices

1. Use Type Hints

from typing import List, Dict, Optional class MyService(BaseCfgModule): def process_items(self, items: List[Dict[str, str]]) -> Optional[str]: pass

2. Handle Configuration Gracefully

def __init__(self): super().__init__() self.config = self.get_config() # Graceful degradation if not self.config or not hasattr(self.config, 'my_service'): self.enabled = False return self.enabled = True self.service_config = self.config.my_service

3. Implement Health Checks

def health_check(self) -> dict: if not self.enabled: return {"status": "disabled", "details": "Service not configured"} try: # Test service connectivity self._test_connection() return {"status": "healthy"} except Exception as e: return {"status": "unhealthy", "details": str(e)}

4. Add Monitoring and Metrics

import time from collections import defaultdict class MonitoredService(BaseCfgModule): def __init__(self): super().__init__() self.metrics = defaultdict(int) self.response_times = [] def tracked_operation(self, data): start_time = time.time() try: result = self._process(data) self.metrics["success"] += 1 return result except Exception as e: self.metrics["error"] += 1 raise finally: duration = time.time() - start_time self.response_times.append(duration) self.metrics["total_requests"] += 1

Integration with Django-CFG

Automatic Discovery

Modules automatically discover your Django-CFG configuration:

# No manual configuration needed! email = DjangoEmailService() # Finds EmailConfig automatically health = DjangoHealthService() # Finds all health-related configs telegram = DjangoTelegramService() # Finds TelegramConfig automatically

Configuration Validation

# api/config.py class MyProjectConfig(DjangoConfig): email: EmailConfig = EmailConfig(...) def validate_modules(self): """Custom validation for modules.""" # Ensure email is configured for production if self.is_prod and not self.email.host: raise ValueError("Email host required for production") # Validate Telegram config if hasattr(self, 'telegram') and self.telegram: if not self.telegram.bot_token: raise ValueError("Telegram bot token is required")

All Modules

Core Infrastructure

ModuleDescriptionOptional
MonitorApplication performance monitoringNo
LoggingStructured loggingNo
Health ChecksAuto-configuring health check endpointsNo

Communication

ModuleDescriptionOptional
Django-RQRedis Queue task processing and schedulingYes (rq)
EmailAuto-configuring email serviceNo
TelegramTelegram bot notificationsYes (httpx)

Commerce

ModuleDescriptionOptional
PaymentsProvider-agnostic one-time payments (Stripe-first) with idempotent webhooks, refunds, and reconciliationYes (stripe)

Admin & UI

ModuleDescriptionOptional
Django AdminType-safe admin with 2234 Material iconsNo
Admin SiteStock Django admin: branding, sidebar navigation, cfg-theme.css (dark by default)No
DRF ThemeTailwind theme for DRF Browsable APINo

Code Generation

ModuleDescriptionOptional
Code GenerationUnified client generation (TS, Python, etc.)No
FastAPI ORMGenerate FastAPI/SQLModel from Django modelsNo

AI & LLM

ModuleDescriptionOptional
LLM IntegrationMulti-provider LLM client with cachingYes
LLM Balance MonitoringProvider balance monitoring with alertsYes

Data & Tools

ModuleDescriptionOptional
Sitemap & IndexNowSitemap sources as a JSON feed for Next.js; IndexNow push to Bing, Yandex and othersNo
CurrencyMulti-currency conversion with MoneyFieldNo
Import/ExportExcel import/export integrationYes (django-import-export)
File CleanupAuto file cleanup on model deleteNo
Tailwind CSSTailwind layout templates and utilitiesNo
Last updated on