Layman’s guide to Signals in Django
What are signals and how to use it in Django?
2 min read
Note: If you are looking for a Full Stack Developer (Django+React), then connect with me on LinkedIn or contact me through my portfolio.
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.
Did you find this article valuable?
Support Dev.Junction by becoming a sponsor. Any amount is appreciated!