← Back to Chapters

Introduction to Signals in Django

? Introduction to Signals in Django

✨ Quick Overview

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.

? Key Concepts

  • Signals enable loose coupling between components
  • They work using sender and receiver patterns
  • Useful for logging, notifications, and automation

? What are Signals?

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.

⚙️ How Do Signals Work?

Signals work through a sender and receiver mechanism. When an action occurs, the signal is sent and all connected receivers are executed.

? Syntax / Theory

Django provides built-in signals such as pre_save, post_save, pre_delete, and post_delete.

? Code Example: Basic Signal Usage

? View Code Example
# 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)

? Code Example: pre_save & post_save

? View Code Example
# 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.")

? Live Output / Explanation

When a new user or book is created, the connected signal receivers automatically execute and perform additional logic without modifying the original save process.

? Use Cases

  • Automatically creating related models
  • Sending notifications or emails
  • Auditing and logging changes

? Interactive Simulator

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.

--:--:-- System ready. Waiting for user input...

✅ Tips & Best Practices

  • Keep signal logic lightweight
  • Use signals for cross-app communication
  • Avoid complex business logic inside signals

? Try It Yourself

  • Create a signal to send a welcome email
  • Track login activity using signals
  • Use m2m_changed for relationship updates