0
0
Djangoframework~5 mins

Why signals enable decoupled communication in Django

Choose your learning style9 modes available
Introduction

Signals let parts of a Django app talk to each other without being tightly connected. This makes the app easier to change and grow.

When you want to run some code after saving a database record without changing the save method.
When you want to notify other parts of your app about an event, like a user logging in.
When you want to keep your code organized by separating event handling from main logic.
When you want to add features later without rewriting existing code.
When you want different parts of your app to react to the same event independently.
Syntax
Django
from django.db.models.signals import signal_name
from django.dispatch import receiver

@receiver(signal_name, sender=ModelName)
def function_name(sender, instance, **kwargs):
    # code to run when signal is sent

@receiver connects your function to the signal.

sender limits the signal to a specific model or source.

Examples
This runs after a Book is saved and prints its title.
Django
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import Book

@receiver(post_save, sender=Book)
def book_saved(sender, instance, **kwargs):
    print(f"Book saved: {instance.title}")
This runs after any request finishes, no sender needed.
Django
from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def request_done(sender, **kwargs):
    print("A request finished.")
Sample Program

This example shows a signal that prints a message when an Article is saved. The signal function is separate from the Article model, so they are loosely connected.

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

class Article(models.Model):
    title = models.CharField(max_length=100)

@receiver(post_save, sender=Article)
def article_saved(sender, instance, **kwargs):
    print(f"Article '{instance.title}' was saved.")

# Simulate saving an Article instance
article = Article(title='Django Signals')
article.save()
OutputSuccess
Important Notes

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

Be careful not to overuse signals, as too many can make debugging harder.

Always connect signals in apps.py or signals.py and import them properly to ensure they work.

Summary

Signals let parts of Django apps communicate without tight links.

This makes apps easier to maintain and extend.

Use signals to react to events like saving or deleting data.