0
0
Djangoframework~5 mins

Signal dispatch process in Django

Choose your learning style9 modes available
Introduction

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 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
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 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')
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.