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:
- Import the necessary modules from
django.dispatch
. - Define a receiver function to handle the signal.
- 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.