In Django, signals provide a way for decoupled applications to get notified when certain actions occur elsewhere in the application. They allow different parts of your application to communicate without tightly coupling them.
Signals are a mechanism in Django that allows certain senders to notify a set of receivers when specific actions occur. Django includes a set of built-in signals and also allows custom signals.
Signals work through a sender and receiver mechanism. When an action occurs, the signal is sent and all connected receivers are executed.
Django provides built-in signals such as pre_save, post_save, pre_delete, and post_delete.
# Import required signal utilities
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
# Create profile only when a new user is created
if created:
Profile.objects.create(user=instance)
# Model and signal imports
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.title
@receiver(pre_save, sender=Book)
def set_default_price(sender, instance, **kwargs):
# Set default price if not provided
if not instance.price:
instance.price = 10.00
@receiver(post_save, sender=Book)
def send_book_created_notification(sender, instance, created, **kwargs):
# Notify when a new book is added
if created:
print(f"A new book titled '{instance.title}' has been added.")
When a new user or book is created, the connected signal receivers automatically execute and perform additional logic without modifying the original save process.
Since we are in a browser, we can't run actual Python code, but we can visualize the flow! Enter a username below to simulate saving a User model and watch the signals fire.
m2m_changed for relationship updates