← Back to Chapters

Connecting Signals with Models

? Connecting Signals with Models

? Quick Overview

Django signals allow applications to react automatically when certain actions occur on models, such as saving or deleting records. By connecting signals to models, developers can perform tasks like creating related objects, modifying data, sending notifications, or cleaning up files without tightly coupling logic to views.

? Key Concepts

  • Signals notify code when specific Django events occur
  • Models represent database tables
  • Signals can be triggered before or after save/delete actions
  • Common signals include pre_save, post_save, and post_delete

? Syntax & Theory

Django provides built-in signals in django.db.models.signals. The @receiver decorator is used to connect a signal to a model and define the logic to run when the signal fires.

? Code Examples

? View Code Example (post_save)
# Create a profile automatically after user creation
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
? View Code Example (pre_save)
# Set default price before saving a book
from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import Book

@receiver(pre_save, sender=Book)
def set_default_price(sender, instance, **kwargs):
    if not instance.price:
        instance.price = 10.00
? View Code Example (post_delete)
# Remove cover file after deleting book
from django.db.models.signals import post_delete
from django.dispatch import receiver
from .models import Book

@receiver(post_delete, sender=Book)
def delete_book_cover(sender, instance, **kwargs):
    if instance.cover:
        instance.cover.delete()

? Interactive Simulation

Scenario: Simulate the post_save code example above. Create a User, and watch the system automatically create a Profile.

> System Waiting... Ready to simulate Django Signals.

? Live Output / Explanation

  • Creating a new user automatically generates a profile
  • Books without prices receive a default value before saving
  • Deleting a book removes its associated cover image

? Interactive Concept Flow

User Action → Model Event → Signal Trigger → Automatic Logic Execution

? Use Cases

  • Auto-create related models
  • Validate or modify data before saving
  • Send notifications or logs after changes
  • Clean up files or related records

✅ Tips & Best Practices

  • Keep signal logic simple and efficient
  • Use signals for cross-cutting concerns
  • Document signal behavior clearly

? Try It Yourself

  • Create a signal that sends an email after saving a model
  • Use pre_save to normalize text fields
  • Attach cleanup logic to post_delete