Today’s Offer Enroll today and get access to premium content.
App Store Google Play
Advanced

What are Django signals and how do you use them?

Django signals are a way to allow decoupled applications to get notified when certain actions occur elsewhere in the application. This is useful for executing actions in response to events.

To use signals, follow these steps:

  1. Import the necessary modules from django.dispatch.
  2. Define a signal receiver function that performs the desired action.
  3. Connect the receiver to the signal using signals.connect().

Here’s an example of a signal that sends an email when a user is created:

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
        print(f'Welcome {instance.username}!')

With this setup, the send_welcome_email function is called automatically whenever a new user is created.