What Signals Are For
Signals are Django's implementation of the observer pattern, allowing certain senders to notify a set of receivers when specific actions occur, without the sender needing any direct knowledge of who's listening. The most commonly used built-in signals are pre_save, post_save, pre_delete, post_delete, and m2m_changed, each dispatched by Django's ORM at the corresponding point in a model's lifecycle, letting you decouple side effects (like sending a welcome email after user creation) from the core save logic itself.
Cricket analogy: Signals are like a stadium's PA announcer broadcasting 'wicket taken' over the loudspeaker without knowing or caring which specific fans in the stands react to it, whether they cheer, groan, or check their fantasy team.
Connecting Receivers
You connect a receiver function to a signal either by calling signal.connect(receiver, sender=SomeModel) explicitly, or more commonly by decorating the function with @receiver(post_save, sender=SomeModel), which Django provides as a shorthand. The sender argument restricts the receiver to fire only for a specific model, and it's essential to import the module containing your receivers (typically in the app's AppConfig.ready() method) so Django actually registers them at startup, since a receiver defined but never imported will simply never run.
Cricket analogy: Using sender=SomeModel is like a fan subscribing to alerts only for their specific team's wickets, not every wicket across the entire tournament, filtering the broadcast to what matters to them.
# signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from .models import UserProfile
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
send_mail(
subject='Welcome!',
message=f'Hi {instance.username}, thanks for signing up.',
from_email='support@example.com',
recipient_list=[instance.email],
)
# apps.py
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'accounts'
def ready(self):
import accounts.signals # noqa: F401 — registers the receiversThe created boolean passed to post_save receivers distinguishes a brand-new insert from an update to an existing row. Forgetting to check if created: is a common bug — it causes the welcome email or profile-creation logic to fire on every single save, not just the first one.
When Not to Use Signals
Signals add indirection: a developer reading the code that calls user.save() has no way of knowing, just by looking at that line, that a profile gets created and an email gets sent elsewhere. For logic that's tightly coupled to a specific action and always needs to happen together, it's often clearer and easier to debug to override the model's save() method directly or handle the logic explicitly in a service function, reserving signals for genuinely decoupled, optional, or cross-app concerns like analytics tracking or cache invalidation.
Cricket analogy: Overusing signals is like a captain making field changes based on hand signals from a coach in the stands that the batsman can't see or anticipate, creating confusion about why the field suddenly shifted.
Signal receivers connected without a sender argument will fire for every model that emits that signal, which can cause unexpected performance issues or side effects across unrelated apps. Always scope receivers with an explicit sender= unless you genuinely need a global listener.
- Signals implement the observer pattern, decoupling senders from receivers via Django's dispatcher.
- post_save, pre_save, pre_delete, post_delete, and m2m_changed are the most common model lifecycle signals.
- @receiver(signal, sender=Model) is the idiomatic way to connect a function to a specific model's signal.
- Receivers must be imported (typically in AppConfig.ready()) or they will never actually be registered.
- The created flag in post_save distinguishes inserts from updates and is essential to check correctly.
- Signals add indirection and can make code harder to trace; prefer explicit calls for tightly coupled logic.
- Reserve signals for decoupled, cross-cutting, or optional behavior like cache invalidation or analytics.
Practice what you learned
1. What design pattern do Django signals implement?
2. Why must signal receiver modules typically be imported inside AppConfig.ready()?
3. What does the `created` argument in a post_save receiver indicate?
4. What happens if a post_save receiver is connected without a sender argument?
5. According to best practice, when should you prefer overriding a model's save() method over using a signal?
Was this page helpful?
You May Also Like
Django Middleware
Understand how Django middleware intercepts every request and response to implement cross-cutting concerns like authentication, security headers, and logging.
Building APIs with Django REST Framework
Learn how Django REST Framework turns Django models and views into robust, browsable JSON APIs using serializers, viewsets, and routers.
Caching in Django
Explore Django's caching framework, from per-view and template-fragment caching to the low-level cache API and choosing a cache backend like Redis.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics