-->

Django Signals

By: Priya Philip 1 month ago

Django Signals allows decoupled (independent) applications get notified when certain events occur elsewhere in the framework with the help of 'signal dispatcher'.  The 'signal dispatcher' is  Django's mechanism used  to send and receive messages between different parts of an application which are instances of Signal, via the connect method.

The Django core also defines a ModelSignal, which is a subclass of Signal that allows the sender to be lazily specified as a string of the app_label.ModelName form.

Django Signals are Used:

  • When many pieces of code may be interested in the same events;
  • When you need to interact with a decoupled application,  e.g.:
    • A Django core model;
    • A model defined by a third-party app

Some of the most useful models’ signals are the following:

  • pre_save/post_save: This signal is sent before/after the method save().
  • pre_delete/post_delete: This signal is sent before or after delete a model’s instance (method delete() is called) .
  • pre_init: This signal is sent before instantiating a model (__init__() method).
  • post_init: This signal is sent when the __init__() method finishes.
  • m2m_changed:This signal is sent when a ManyToManyField on a model is changed.       

There are two key concepts: the Sender and the Receiver:

Sender :-  must either be a Python object, or None to receive events from any sender.

Receiver :-  must be a function or an instance method which is to receive signals.

Listening to signals:

To receive a signal, register a receiver function using the Signal.connect() method. The receiver function is called when the signal is sent.

Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)
Parameters:
  • receiver – The callback function which will be connected to this signal. See Receiver functions for more information.
  • sender – Specifies a particular sender to receive signals from. See Connecting to signals sent by specific senders for more information.
  • weak – Django stores signal handlers as weak references by default. Thus, if your receiver is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect() method.
  • dispatch_uid – A unique identifier for a signal receiver in cases where duplicate signals may be sent. See Preventing duplicate signalsfor more information.

Let’s see how this works by registering a signal that gets called after each HTTP request is finished. We’ll be connecting to the request_finished signal.

Receiver functions

First, define a receiver function. A receiver can be any Python function or method:

def my_callback(sender, **kwargs):
    print("Request finished!")

Notice that the function takes a sender argument, along with wildcard keyword arguments (**kwargs); all signal handlers must take these arguments.

The **kwargs argument, all signals send keyword arguments, and may change those keyword arguments at any time. In the case of request_finished, it’s documented as sending no arguments, which means we might be tempted to write our signal handling as my_callback(sender).

This would be wrong – in fact, Django will throw an error if you do so. That’s because at any point arguments could get added to the signal and your receiver must be able to handle those new arguments.

Connecting receiver functions

There are two ways you can connect a receiver to a signal. You can take the manual connect route:


from django.core.signals import request_finished

request_finished.connect(my_callback)

Alternatively, you can use a receiver() decorator:

receiver(signal)
Parameters:signal – A signal or a list of signals to connect a function to. 

Here’s how you connect with the decorator:


from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def my_callback(sender, **kwargs):
    print("Request finished!")

Now, our my_callback function will be called each time a request finishes.

Connecting to signals sent by specific senders

Some signals get sent many times, but you’ll only be interested in receiving a certain subset of those signals. For example, consider the django.db.models.signals.pre_save signal sent before a model gets saved. Most of the time, you don’t need to know when any model gets saved – just when one specific model is saved.

In these cases, you can register to receive signals sent only by particular senders. In the case of django.db.models.signals.pre_save, the sender will be the model class being saved, so you can indicate that you only want signals sent by some model:


from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel


@receiver(pre_save, sender=MyModel)
def my_handler(sender, **kwargs):
    ...

The my_handler function will only be called when an instance of MyModel is saved.

Different signals use different objects as their senders.

Preventing duplicate signals

In some circumstances, the code connecting receivers to signals may run multiple times. This can cause your receiver function to be registered more than once, and thus called multiple times for a single signal event.

If this behavior is problematic (such as when using signals to send an email whenever a model is saved), pass a unique identifier as the dispatch_uid argument to identify your receiver function. This identifier will usually be a string, although any hashable object will suffice. The end result is that your receiver function will only be bound to the signal once for each unique dispatch_uid value:


from django.core.signals import request_finished

request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")

Comments

Wish to hire us?

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.