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

What is the purpose of Django's signals?

Django signals allow certain senders to notify a set of receivers when certain actions have taken place. This is useful for decoupling applications. Here’s how to use signals:

  1. Import the necessary modules from django.dispatch.
  2. Define a receiver function to handle the signal.
  3. Connect the receiver to a signal using the connect method.

Example:

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

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
    print('Model saved!')

This function runs every time an instance of MyModel is saved.