Layman’s guide to Signals in Django
What are signals and how to use it in Django?
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
signal
through adispatch
device, and you will receive that signal using areceiver
.Now it's your decision to make, how you will respond to that
signal
.
Similarly, in Django signals
are fired at some defined actions, and you can receive the signals
using receiver
decorators.
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 - django.db.models.signals
.
pre_save
&post_save
signals, respectively sent before and after a model’ssave()
method is called.pre_delete
&post_delete
, respectively sent before and after a model’sdelete()
method or queryset’sdelete()
method is called.request_started
&request_finished
, respectively sent when Django starts and finishes anHTTP
request.m2m_changed
, sent when aManyToManyField
on a model is changed.
Using a signal
:
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 @receiver
decorator.
- Using
connect()
method:
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)
- Using
@receiver
decorator:
from django.core.sigoaLs import pre_save
from django.dispatch import receiver
@receiver(pre_save)
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.
Social Links
LinkedIn: https://www.linkedin.com/in/mnamegaurav/
Website: https://gaurav.devjunction.in/
GitHub: https://github.com/mnamegaurav
Instagram: https://www.instagram.com/mnamegaurav/
Twitter: https://twitter.com/mnamegaurav