Intermediate
What are Django signals and how are they used?
Django signals are a powerful feature that allows certain senders to notify a set of receivers when specific actions have taken place. This mechanism facilitates decoupled applications, enabling components to communicate without requiring them to be directly linked.
To use Django signals, follow these steps:
- Define a Signal: Use Django's built-in signals or create your own using
signals.py
. - Connect Receivers: Define functions that will handle the signal and connect them using the
connect
method. - Send Signals: Trigger the signal at the appropriate action within your application.
For example, you might want to send an email confirmation whenever a new user registers:
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 send_welcome_email(sender, instance, created, **kwargs):
if created:
# logic to send email
This code snippet sets up a signal that listens for the creation of a new user and executes the send_welcome_email
function when a user is created. Signals can greatly enhance the modularity of your Django application.