Events & Signals
Event-Driven Architecture
Use Django signals to decouple business logic and trigger actions on model events (e.g., post_save, pre_delete).
- Define signal handlers in
signals.pyor relevant app modules. - Connect signals in
apps.pyor viaready()method.
Example:
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import User
@receiver(post_save, sender=User)
def send_welcome_email(sender, instance, created, **kwargs):
if created:
# Send welcome email
pass
Naming Conventions
- Use descriptive names for signal handlers (e.g.,
send_welcome_email). - Group related signals and handlers by app or feature.
Organization
- Place signal handlers in
signals.pyor a dedicated module. - Document signal usage and side effects for maintainability.
Best Practices
- Avoid heavy logic in signal handlers; use services for complex operations.
- Disconnect signals in tests to avoid side effects.
- Write tests for signal handlers and event-driven workflows.