What Are Signals in Django: Simple Explanation and Example
signals are a way to let parts of your app communicate automatically when certain actions happen, like saving or deleting data. They let you run custom code in response to these events without changing the original code that triggered them.How It Works
Think of Django signals like a doorbell in a house. When someone presses the doorbell (an event happens), it sends a signal to notify the people inside (other parts of your app). Those people can then respond by opening the door or doing something else.
In Django, signals let different parts of your app listen for specific events, such as when a database record is saved or deleted. When the event occurs, Django sends a signal, and any function connected to that signal will run automatically. This helps keep your code organized and lets you add extra behavior without changing the main logic.
Example
This example shows how to use Django's post_save signal to print a message whenever a new user is created.
from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def user_created(sender, instance, created, **kwargs): if created: print(f"New user created: {instance.username}")
When to Use
Use signals when you want to run extra code automatically after certain actions happen, without changing the original code that performs those actions. For example:
- Sending a welcome email after a user signs up.
- Updating related data when a model changes.
- Logging changes or auditing actions.
Signals help keep your app modular and clean by separating these extra tasks from core logic.
Key Points
- Signals notify parts of your app when events happen.
- They help keep code modular by separating event responses.
- Django provides built-in signals like
post_saveandpre_delete. - You connect functions to signals using decorators or
connect(). - Signals run automatically when their event occurs.