0
0
Djangoframework~5 mins

Custom signals in Django

Choose your learning style9 modes available
Introduction

Custom signals let you send messages inside your Django app when something happens. This helps different parts of your app talk to each other without being tightly connected.

You want to run extra code after saving a model without changing the model code.
You need to notify other parts of your app when a user logs in or out.
You want to keep your code organized by separating actions triggered by events.
You want to add logging or analytics when certain actions happen in your app.
Syntax
Django
from django.dispatch import Signal

# Define a custom signal
my_signal = Signal()

# Define a receiver function
def my_receiver(sender, **kwargs):
    print(f"Signal received with args: {kwargs}")

# Connect the receiver to the signal
my_signal.connect(my_receiver)

# Send the signal
my_signal.send(sender=None, arg1='hello', arg2='world')

Signal: This is the message you send.

Receiver: This is the function that listens and reacts to the signal.

Examples
This example shows a signal without any extra data sent.
Django
from django.dispatch import Signal

# Create a signal without arguments
simple_signal = Signal()

# Receiver function
def receiver(sender, **kwargs):
     print("Simple signal received")

# Connect and send
simple_signal.connect(receiver)
simple_signal.send(sender=None)
This example sends a username with the signal and the receiver greets the user.
Django
from django.dispatch import Signal

# Signal with arguments
user_logged_in = Signal()

def greet_user(sender, user, **kwargs):
    print(f"Welcome {user}!")

user_logged_in.connect(greet_user)
user_logged_in.send(sender=None, user='Alice')
Sample Program

This program creates a custom signal called order_completed. When the signal is sent with an order ID, the receiver prints a message to notify shipping.

Django
from django.dispatch import Signal

# Define a custom signal with one argument
order_completed = Signal()

# Receiver function that reacts to the signal
def notify_shipping(sender, order_id, **kwargs):
    print(f"Order {order_id} completed. Notify shipping department.")

# Connect the receiver to the signal
order_completed.connect(notify_shipping)

# Simulate sending the signal when an order is done
order_completed.send(sender=None, order_id=12345)
OutputSuccess
Important Notes

Always connect your receiver functions before sending signals.

Use providing_args to document what data your signal sends, but Django does not enforce it.

Signals help keep your code clean by separating event handling from main logic.

Summary

Custom signals let parts of your Django app communicate without tight links.

Define signals, write receivers, connect them, then send signals when needed.

This helps organize code and add features like notifications or logging easily.