Introduction & Analogy:
What is a
signal in Django ?
Let's say you and your friend have planned a robbery. You will enter the bank and your friend will be waiting outside.
As soon as police arrives, your friend will give you a
dispatchdevice, and you will receive that signal using a
Now it's your decision to make, how you will respond to that
Similarly, in Django
signals are fired at some defined actions, and you can receive the
Built-in Signals in Django:
Django provides a set of built-in
signals that lets your
code get notified from Django of certain actions. You can import these signals from here -
post_savesignals, respectively sent before and after a model’s
save()method is called.
post_delete, respectively sent before and after a model’s
delete()method or queryset’s
delete()method is called.
request_finished, respectively sent when Django starts and finishes an
m2m_changed, sent when a
ManyToManyFieldon a model is changed.
In most of the cases, we use
signals for model actions, but you can define your own custom
signal on a custom action.
We can receive a
signal in two ways, first is through
connect() method and second is through
In the below example,
function_to_execute will run just before any model instance will be saved.
from django.core.signals import pre_save def function_to_execute(sender, **kwargs): print("Received the signal!") pre_save.connect(function_to_execute)
from django.core.sigoaLs import pre_save from django.dispatch import receiver def function_to_execute(sender, **kwargs): print("Received the signal!")
Any doubts? Write it down in the comments.
For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.