0
0
Djangoframework~5 mins

Connecting signal handlers in Django

Choose your learning style9 modes available
Introduction

Connecting signal handlers lets your Django app react automatically when certain actions happen, like saving a record. It helps keep your code organized and responsive.

You want to send a welcome email right after a new user signs up.
You need to update related data whenever a model instance is saved.
You want to log changes automatically when a database record is deleted.
You want to trigger background tasks after a model is created or updated.
Syntax
Django
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=YourModel)
def your_handler(sender, instance, created, **kwargs):
    if created:
        # code to run after a new instance is saved
        pass

The @receiver decorator connects your function to a signal.

The sender argument specifies which model triggers the signal.

Examples
This example sends a welcome email when a new User is created.
Django
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import User

@receiver(post_save, sender=User)
def send_welcome_email(sender, instance, created, **kwargs):
    if created:
        print(f"Welcome email sent to {instance.email}")
This example logs a message before an Article is deleted.
Django
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from myapp.models import Article

@receiver(pre_delete, sender=Article)
def log_article_deletion(sender, instance, **kwargs):
    print(f"Article titled '{instance.title}' is about to be deleted.")
Sample Program

This code defines a Product model and connects a signal handler to post_save. When a product is saved, if its stock is less than 5, it prints a warning message.

Django
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Product(models.Model):
    name = models.CharField(max_length=100)
    stock = models.IntegerField(default=0)

@receiver(post_save, sender=Product)
def notify_low_stock(sender, instance, **kwargs):
    if instance.stock < 5:
        print(f"Warning: Low stock for product '{instance.name}'")

# Simulate saving products
p1 = Product(name='Pen', stock=10)
p1.save()
p2 = Product(name='Notebook', stock=3)
p2.save()
OutputSuccess
Important Notes

Signals run synchronously by default, so avoid long tasks inside handlers.

Always specify the sender to avoid handling signals from unrelated models.

Summary

Signals let your app react automatically to model events.

Use @receiver to connect handlers to signals.

Check the created flag to run code only on new records.