=======Signals=======.. module:: django.dispatch:synopsis: Signal dispatchDjango includes a "signal dispatcher" which helps decoupled applications getnotified when actions occur elsewhere in the framework. In a nutshell, signalsallow certain *senders* to notify a set of *receivers* that some action hastaken place. They're especially useful when many pieces of code may beinterested in the same events.For example, a third-party app can register to be notified of settingschanges::from django.apps import AppConfigfrom django.core.signals import setting_changeddef my_callback(sender, **kwargs):print("Setting changed!")class MyAppConfig(AppConfig):...def ready(self):setting_changed.connect(my_callback)Django's :doc:`built-in signals </ref/signals>` let user code get notified ofcertain actions.You can also define and send your own custom signals. See:ref:`defining-and-sending-signals` below... warning::Signals give the appearance of loose coupling, but they can quickly lead tocode that is hard to understand, adjust and debug.Where possible you should opt for directly calling the handling code,rather than dispatching via a signal.Listening to signals====================To receive a signal, register a *receiver* function using the:meth:`Signal.connect` method. The receiver function is called when the signalis sent. All of the signal's receiver functions are called one at a time, inthe order they were registered... method:: Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None):param receiver: The callback function which will be connected to thissignal. See :ref:`receiver-functions` for more information.:param sender: Specifies a particular sender to receive signals from. See:ref:`connecting-to-specific-signals` for more information.:param weak: Django stores signal handlers as weak references bydefault. Thus, if your receiver is a local function, it may begarbage collected. To prevent this, pass ``weak=False`` when you callthe signal's ``connect()`` method.:param dispatch_uid: A unique identifier for a signal receiver in caseswhere duplicate signals may be sent. See:ref:`preventing-duplicate-signals` for more information.Let's see how this works by registering a signal thatgets called after each HTTP request is finished. We'll be connecting to the:data:`~django.core.signals.request_finished` signal... _receiver-functions:Receiver functions------------------First, we need to define a receiver function. A receiver can be any Pythonfunction or method::def my_callback(sender, **kwargs):print("Request finished!")Notice that the function takes a ``sender`` argument, along with wildcardkeyword arguments (``**kwargs``); all signal handlers must take these arguments.We'll look at senders :ref:`a bit later <connecting-to-specific-signals>`, butright now look at the ``**kwargs`` argument. All signals send keywordarguments, and may change those keyword arguments at any time. In the case of:data:`~django.core.signals.request_finished`, it's documented as sending noarguments, 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'sbecause at any point arguments could get added to the signal and your receivermust be able to handle those new arguments... _connecting-receiver-functions:Connecting receiver functions-----------------------------There are two ways you can connect a receiver to a signal. You can take themanual connect route::from django.core.signals import request_finishedrequest_finished.connect(my_callback)Alternatively, you can use a :func:`receiver` decorator:.. function:: receiver(signal, **kwargs):param signal: A signal or a list of signals to connect a function to.:param kwargs: Wildcard keyword arguments to pass to a:ref:`function <receiver-functions>`.Here's how you connect with the decorator::from django.core.signals import request_finishedfrom 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... admonition:: Where should this code live?Strictly speaking, signal handling and registration code can live anywhereyou like, although it's recommended to avoid the application's root moduleand its ``models`` module to minimize side-effects of importing code.In practice, signal handlers are usually defined in a ``signals``submodule of the application they relate to. Signal receivers areconnected in the :meth:`~django.apps.AppConfig.ready` method of yourapplication :ref:`configuration class <configuring-applications-ref>`. Ifyou're using the :func:`receiver` decorator, import the ``signals``submodule inside :meth:`~django.apps.AppConfig.ready`, this will implicitlyconnect signal handlers::from django.apps import AppConfigfrom django.core.signals import request_finishedclass MyAppConfig(AppConfig):...def ready(self):# Implicitly connect signal handlers decorated with @receiver.from . import signals# Explicitly connect a signal handler.request_finished.connect(signals.my_callback).. note::The :meth:`~django.apps.AppConfig.ready` method may be executed more thanonce during testing, so you may want to :ref:`guard your signals fromduplication <preventing-duplicate-signals>`, especially if you're planningto send them within tests... _connecting-to-specific-signals:Connecting to signals sent by specific senders----------------------------------------------Some signals get sent many times, but you'll only be interested in receiving acertain subset of those signals. For example, consider the:data:`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 -- justwhen one *specific* model is saved.In these cases, you can register to receive signals sent only by particularsenders. In the case of :data:`django.db.models.signals.pre_save`, the senderwill be the model class being saved, so you can indicate that you only wantsignals sent by some model::from django.db.models.signals import pre_savefrom django.dispatch import receiverfrom 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; you'll need to consultthe :doc:`built-in signal documentation </ref/signals>` for details of eachparticular signal... _preventing-duplicate-signals:Preventing duplicate signals----------------------------In some circumstances, the code connecting receivers to signals may runmultiple times. This can cause your receiver function to be registered morethan once, and thus called as many times for a signal event. For example, the:meth:`~django.apps.AppConfig.ready` method may be executed more than onceduring testing. More generally, this occurs everywhere your project imports themodule where you define the signals, because signal registration runs as manytimes as it is imported.If this behavior is problematic (such as when using signals tosend an email whenever a model is saved), pass a unique identifier asthe ``dispatch_uid`` argument to identify your receiver function. Thisidentifier will usually be a string, although any hashable object willsuffice. The end result is that your receiver function will only bebound to the signal once for each unique ``dispatch_uid`` value::from django.core.signals import request_finishedrequest_finished.connect(my_callback, dispatch_uid="my_unique_identifier").. _defining-and-sending-signals:Defining and sending signals============================Your applications can take advantage of the signal infrastructure and provideits own signals... admonition:: When to use custom signalsSignals are implicit function calls which make debugging harder. If thesender and receiver of your custom signal are both within your project,you're better off using an explicit function call.Defining signals----------------.. class:: Signal()All signals are :class:`django.dispatch.Signal` instances.For example::import django.dispatchpizza_done = django.dispatch.Signal()This declares a ``pizza_done`` signal.Sending signals---------------There are two ways to send signals in Django... method:: Signal.send(sender, **kwargs).. method:: Signal.send_robust(sender, **kwargs)To send a signal, call either :meth:`Signal.send` (all built-in signals usethis) or :meth:`Signal.send_robust`. You must provide the ``sender`` argument(which is a class most of the time) and may provide as many other keywordarguments as you like.For example, here's how sending our ``pizza_done`` signal might look::class PizzaStore:...def send_pizza(self, toppings, size):pizza_done.send(sender=self.__class__, toppings=toppings, size=size)...Both ``send()`` and ``send_robust()`` return a list of tuple pairs``[(receiver, response), ... ]``, representing the list of called receiverfunctions and their response values.``send()`` differs from ``send_robust()`` in how exceptions raised by receiverfunctions are handled. ``send()`` does *not* catch any exceptions raised byreceivers; it simply allows errors to propagate. Thus not all receivers maybe notified of a signal in the face of an error.``send_robust()`` catches all errors derived from Python's ``Exception`` class,and ensures all receivers are notified of the signal. If an error occurs, theerror instance is returned in the tuple pair for the receiver that raised the error.The tracebacks are present on the ``__traceback__`` attribute of the errorsreturned when calling ``send_robust()``.Disconnecting signals=====================.. method:: Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)To disconnect a receiver from a signal, call :meth:`Signal.disconnect`. Thearguments are as described in :meth:`.Signal.connect`. The method returns``True`` if a receiver was disconnected and ``False`` if not. When ``sender``is passed as a lazy reference to ``<app label>.<model>``, this method alwaysreturns ``None``.The ``receiver`` argument indicates the registered receiver to disconnect. Itmay be ``None`` if ``dispatch_uid`` is used to identify the receiver.