Django includes a "signal dispatcher" that helps decoupled applications get notified when framework-level actions occur. The most widely used signals are model signals: post_save, pre_save, post_delete, and pre_delete.
Whenever a new User instance is created, we want to automatically generate a corresponding AuthorProfile record without cluttering our registration views:
# accounts/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from blog.models import AuthorProfile
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_or_update_user_profile(sender, instance, created, **kwargs):
"""Listens for new user creation and initializes empty profile."""
if created:
# Create profile record for new user
AuthorProfile.objects.create(user=instance)
else:
# Save profile if existing user is modified
if hasattr(instance, 'profile'):
instance.profile.save()
Signals must be imported inside your AppConfig.ready() method so Django connects receivers at boot time:
# accounts/apps.py
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'accounts'
def ready(self):
# Connect signal receivers
import accounts.signals
Do not overuse signals! Overusing signals makes code hard to trace, debug, and test because side effects occur "magically" behind the scenes. If logic is strictly internal to a model, explicitly override save() on the model instead.
Broaden your backend architecture, REST API design, and production engineering expertise:
Hook into model lifecycle events with post_save and post_delete.
Dispatch asynchronous jobs from signals without blocking HTTP threads.
Auto-create user profile records whenever a new User instance is registered.
Discuss signals vs overriding model save() in technical interviews.