Signals  :Django

Photo by Faisal on Unsplash

Signals :Django

Django has a "signal dispatcher" which helps two separate applications to get notified when any action occurs anywhere within the framework.

These are useful in that scenario where the piece of code is interested in the same piece of the event.

Django provides a set of built-in signals that let user code get notified by Django itself of certain actions.

  • django.db.models.signals.pre_save & django.db.models.signals.post_save Sent before or after model's save() method
  • django.db.models.signals.pre_delete & django.db.models.signals.post_delete Sent before and after model's delete() method
  • django.db.models.signals.m2m_changed Sent when ManyToManyField in model is changed.

See the complete list of built-in signal

We can also define and send our own custom signals check here

How to use Signals

There are many ways to use signals, we will be using the "@receiver" decorator.

Here is an Example

image.png

The receiver decorator tells the code that the function("create_profile") is about to receive a signal(post_save signal in this case).

Signals.py file

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import User, Profile

@receiver(post_save, sender=User)
def post_save_create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(User=instance)

inside apps.py

create a ready function and import signal there

image.png

add this line in init.py file of the app

default_app_config = "users.apps.UsersConfig"

Go to admin and try creating new user as soon as you hit the save button profile will also get created

Thanks for reading

If this article needs improvement suggest us via comments.