Signals let parts of your Django app talk to each other when something happens. The dispatch process sends these messages to the right listeners.
Signal dispatch process in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
from django.dispatch import Signal # Define a signal my_signal = Signal() # Define a receiver function def my_receiver(sender, **kwargs): print("Signal received with", kwargs) # Connect the receiver to the signal my_signal.connect(my_receiver) # Send the signal my_signal.send(sender=None, arg1='hello', arg2='world')
Signals are defined using Signal().
Receivers are functions that get called when the signal is sent.
Examples
Django
from django.db.models.signals import post_save from django.dispatch import receiver from myapp.models import MyModel @receiver(post_save, sender=MyModel) def my_handler(sender, instance, created, **kwargs): if created: print(f"New {sender.__name__} created: {instance}")
Django
from django.dispatch import Signal custom_signal = Signal() def listener(sender, **kwargs): print("Custom signal received") custom_signal.connect(listener) custom_signal.send(sender=None)
Sample Program
This program defines a signal for user login and a receiver that greets the user. When the signal is sent, the greeting prints.
Django
from django.dispatch import Signal # Define a signal user_logged_in = Signal() # Define a receiver function def greet_user(sender, user, **kwargs): print(f"Welcome, {user}!") # Connect the receiver to the signal user_logged_in.connect(greet_user) # Simulate sending the signal user_logged_in.send(sender=None, user='Alice')
Important Notes
Always connect receivers before sending signals to ensure they catch the message.
Use sender to filter signals from specific sources.
Signals help keep your code organized and decoupled.
Summary
Signals send messages between parts of a Django app.
The dispatch process calls connected receivers when a signal is sent.
Use signals to react automatically to events like saving or deleting data.
Practice
1. What is the main purpose of Django signals in the signal dispatch process?
easy
Solution
Step 1: Understand what signals do
Django signals send messages between parts of an app when something happens.Step 2: Identify the purpose of signals
Signals let parts of the app react automatically to events like saving or deleting data.Final Answer:
To allow different parts of an app to communicate automatically when events happen -> Option AQuick Check:
Signals enable automatic communication [OK]
Hint: Signals connect events to actions automatically [OK]
Common Mistakes:
- Thinking signals store data
- Confusing signals with UI elements
- Believing signals handle HTTP requests
2. Which of the following is the correct way to connect a receiver function to a Django signal?
easy
Solution
Step 1: Recall the syntax for connecting signals
In Django, you connect a receiver to a signal using signal.connect(receiver, sender=...).Step 2: Match the correct method call
signal.connect(receiver_function, sender=ModelClass) uses signal.connect with the receiver function and sender, which is correct.Final Answer:
signal.connect(receiver_function, sender=ModelClass) -> Option AQuick Check:
Use signal.connect to attach receivers [OK]
Hint: Remember: signal.connect(receiver, sender) [OK]
Common Mistakes:
- Calling connect on the receiver instead of the signal
- Using send instead of connect to attach receivers
- Mixing up sender and receiver parameters
3. Given this code snippet, what will be printed when a new User instance is saved?
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def user_saved(sender, instance, created, **kwargs):
if created:
print(f"User {instance.username} created")
else:
print(f"User {instance.username} updated")
user = User(username='alice')
user.save()medium
Solution
Step 1: Understand the post_save signal and receiver
The receiver listens for post_save on User. It prints 'created' if the instance is new.Step 2: Analyze the save call
Creating a new User and calling save triggers post_save with created=True, so it prints 'User alice created'.Final Answer:
User alice created -> Option BQuick Check:
New save triggers created=True message [OK]
Hint: post_save with created=True means new instance saved [OK]
Common Mistakes:
- Assuming updated message prints on new save
- Thinking receiver is not connected automatically
- Ignoring the created flag in the receiver
4. What is wrong with this signal receiver code when trying to target deletes from a specific model only?
from django.db.models.signals import pre_delete
def my_receiver(sender, instance, **kwargs):
print(f"Deleting {instance}")
pre_delete.connect(my_receiver)medium
Solution
Step 1: Check the connect call parameters
The connect call lacks the sender argument, so it connects to all senders.Step 2: Identify why it doesn't target a specific model
Without specifying sender, the receiver runs for deletes on any model. Adding sender=ModelClass limits it to that model.Final Answer:
Missing sender argument in connect call -> Option CQuick Check:
Always specify sender for model-specific receivers [OK]
Hint: Always specify sender in connect unless you want all senders [OK]
Common Mistakes:
- Thinking @receiver decorator is required
- Believing pre_delete signal does not exist
- Expecting receiver to return a value
5. You want to send a custom signal when a blog post is published. Which steps correctly describe the signal dispatch process to achieve this?
hard
Solution
Step 1: Define a custom Signal
Create a Signal instance to represent the blog post published event.Step 2: Connect a receiver function
Use the @receiver decorator or signal.connect to attach a function that reacts to the signal.Step 3: Send the signal when publishing
Call signal.send(sender=..., instance=...) at the point where the blog post is published.Final Answer:
Define a custom Signal, connect a receiver with @receiver decorator, then send the signal when publishing -> Option DQuick Check:
Custom signal + receiver + send = correct process [OK]
Hint: Custom signals need definition, connection, and sending [OK]
Common Mistakes:
- Trying to use only built-in signals for custom events
- Calling receiver directly without signal
- Overriding save without signals when signals are needed
