1.

What are the roles of receiver and sender in signals?

Answer»

The Django Signals is a tactic to notify decoupled APPLICATIONS when certain events occur. The Django Signal is used when many pieces of code may be interested in the same events or when you need to interact with decoupled applications like A Django core model or A model defined by a third-party app.

Two key ELEMENTS the Senders and the receivers are in the signals machinery. The sender is responsible to dispatch a signal, and the receiver is the one who receives this signal and then performs something.

A receiver can be a function or an instance METHOD to receive signals. A sender can be a Python object or None to receive events from any sender.

Via the connect method, the connection between the receivers and senders is done through 'Signal Dispatchers', which are instances of Signal.

The Django core defines a ModelSignal, a subclass of Signal that allows the sender to lazily specify as a string of the app_label.ModelName form.

You need to register a receiver function that gets called when the signal is sent by USING the Signal.connect() method to receive a signal.

Let us see a post_save built-in signal. The code for post_save is stored in the django.db.models.signals module. This signal is fired right after a model finishes executing its save method.

//models.py from django.contrib.auth.models IMPORT User from django.db.models.signals import post_savedef save_profile(sender, instance, **kwargs):    instance.profile.save()post_save.connect(save_profile, sender=User)

Here save_profile is a receiver, User is the sender and post_save is the signal. Wherever a User instance finalizes the execution of the save method, save_profile function will be executed.



Discussion

No Comment Found