Django Signals

Abhishek Mani
2 min readJan 27, 2021

--

This story is about the basics of django signals , for instance we can use it for creating the profile .. in a nutshell signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.

When we want different other methods to be executed at the same time when a particular method is executed , then this is where django signals comes into picture

Django Signals

Lets understand it with a short example:

Starting with a sample django project :

  • Django-admin startproject sampleProject
  • Cd sampleProject
  • Use : python manage.py startapp demo

sample project and app is up and ready

Lets move to models.py file inside our app folder i.e demo

In models.py file use the below code snippet(visit below repo for better code visuality):

from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user=
models.OneToOneField(User,
on_delete=models.CASCADE,null=True,blank=True)
first_name = models.CharField(max_length=200,null=True,blank=True)
last_name = models.CharField(max_length=200,null=True,blank=True) phone = models.CharField(max_length=200,null=True,blank=True)def __str__(self):
return str(self.user)

Create another File as signals.py file inside app here ie.,demo(visit below link for better code visuality)

from django.db.models.signals import post_savefrom django.contrib.auth.models import Userfrom django.dispatch import receiverfrom .models import Profile@receiver(post_save,sender=User)def create_profile(sender,instance,created,**kwargs):   if created:       Profile.objects.create(user = instance)       print('profile created')@receiver(post_save,sender=User)def update_profile(sender,instance,created,**kwargs):  if created==False:  instance.profile.save()  print('profile Updated')

Now Just Create a superuser and enter the credentials use below command:

Python manage.py createsuperuser

now run the app using :

python manage.py runsevrer

Result:

Creating a user will automatically create the profile for user also.

Hence very useful in case when we want multiple method or functionality to get executed with just single event or action.

Thank you!

--

--

Abhishek Mani
Abhishek Mani

Written by Abhishek Mani

I am software developer , experienced in python web app development , javascript , data science

No responses yet