signals in django models code example
Example 1: django builtin signals
django post_save signals
Let’s have a look on the post_save built-in signal. Its code lives in the django.db.models.signals module. This particular signal fires right after a model finish executing its save method.
from django.contrib.auth.models import User
from django.db.models.signals import post_save
def save_profile(sender, instance, **kwargs):
instance.profile.save()
post_save.connect(save_profile, sender=User)
Another way to register a signal, is by using the @receiver decorator:
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 save_profile(sender, instance, **kwargs):
instance.profile.save()
Example 2: django signals
what are django signals?
The Django Signals is a strategy to allow decoupled applications to get notified when certain events occur
There are two key elements in the signals machinary: the senders and the receivers. As the name suggests, the sender is the one responsible to dispatch a signal, and the receiver is the one who will receive this signal and then do something.
A receiver must be a function or an instance method which is to receive signals.
A sender must either be a Python object, or None to receive events from any sender.
The connection between the senders and the receivers is done through “signal dispatchers”, which are instances of Signal, via the connect method.
So to receive a signal, you need to register a receiver function that gets called when the signal is sent by using the Signal.connect() method.