Signals let parts of your Django app talk to each other when something happens. The dispatch process sends these messages to the right listeners.
You want to run code automatically after saving a database record.
You need to update related data when a user logs in.
You want to send notifications when a new object is created.
You want to keep different parts of your app loosely connected.
You want to trigger cleanup tasks when an object is deleted.
Syntax
Django
from django.dispatch import Signal
# Define a signal
my_signal = Signal()
# Define a receiver functiondef 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
This example listens for when a new database record is saved and prints a message.
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}")
Shows a simple custom signal being sent and received.
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 functiondef 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')
OutputSuccess
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/5)
1. What is the main purpose of Django signals in the signal dispatch process?
easy
A. To allow different parts of an app to communicate automatically when events happen
B. To store data in the database
C. To create user interface elements
D. To handle HTTP requests directly
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 A
Quick 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
A. signal.connect(receiver_function, sender=ModelClass)
B. receiver_function.connect(signal, sender=ModelClass)
C. signal.send(receiver_function, sender=ModelClass)
D. receiver_function.send(signal, sender=ModelClass)
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 A