Layman’s guide to Signals in Django

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 a dispatch device, and you will receive that signal using a receiver.

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’s save() method is called.

  • pre_delete & post_delete, respectively sent before and after a model’s delete() method or queryset’s delete() method is called.

  • request_started & request_finished, respectively sent when Django starts and finishes an HTTP request.

  • m2m_changed, sent when a ManyToManyField 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!") 
  • Using @receiver decorator:
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!