Django Signals


Django Signals


In this article, Iam going to explain about Django Signals.It’s the most Important topic in Django.So let’s start our article and please read carefully to make a Django project.

Introduction

The Django Signals is basically a technic to allow Django applications to get notified when certain events occur. Let’s assume you want to create a Jinja2 page everytime a given model instance is updated, but there are many more pages in your project’s base that this model can be updated. 

We could  do that by using Django signals, using or pick some pieces of code to be executed everytime when there are a  specific model’s method is triggered like save,update,create,view operation’s in  Model.

Most Commonly used cases is when you have executed the Django Model in our project by using the User Database  through the default Sqlite database which uses one-to-one relationship. Usually Django signal uses the“signal dispatcher” to listen for the operation event’s like Projects post_save,pre_save etc event's used to update or manipulate the Project instance’s in Database.

I have covered this whole database topic  in my  another post, For help and for reading complete concept read here:-

https://www.tech-programmer.com/2020/03/build-curdcrud-projects-in-python-and.html

In this tutorial I will show you all guys,about the built-in signals and  I will show some instructions to use properly the Django Signal in the Projects.

 


Why we Should Use Django Signals ?


Why and When we have to use Django signals, given some reasons :-
  • When there are many coding places and  happening’s same events in a page.
  • When all you have to interact and want to know that yourDjango application Model is worked or not, e.g. :-
    • First we have to create Django model got this.
    • We could define our model defined through a third-party libraries.

 


Working of Django Signals ?


If you all guys know the basic of Django Concept, After that we have continue our tutorial becauseWithout knowing the Django basics all this is waste and you don’t understand so please learn it first.

So let’s know the tutorial on Working of Django Signal.

There are two key elements in the signals library: the senders and the receivers. As the name suggests, the sender is the one responsible to dispatch a signal, and the receiver is the one who will receive this signal and then both  do something like show message or  other.

·         receiver must be a function or an instance method which is to receive signals.
·         sender must by either send object’s, or None to receive events from any sender.

The connection between the senders and the receivers is worked through “signal dispatchers”, which are instances of Django Signal, via the connect method.

The Django basically also defines a ModelSignal, which is a subclass of Signal that allows the sender to work as a string of the app_label.ModelName form. If you want to use the Signal class to create custom signals or your own signals in Django Project.

If want to receive a signal, you need to create a  receiver function and  that gets called when the signal is sent by using sender through  using the Signal.connect() method.

 


Receiver and Sender





First we have to see the working of the post_save built-in signal. Import the library of the django.db.models.signals module in the file. This post_save built-in signal to save the model in the Django projects.



from django.contrib.auth.models import User

from django.db.models.signals import post_save


defprofile(sender,value,**kwargs):

                                 value.profile.save()

post_save.connect(profile,sender=User)

 
In the example above, profile is our receiver function, User is the sender and post_save is the signal. 

You can read it as: Everytime when a User instance finalize the execution of its save method, the save_profile function will be executed.

If you express the sender argument like this: post_save.connect(save_profile), the profile function will be executed after any Django model executes the save method.

Another way to register a signal, is by using the @receiver decorator:-

defreceiver(signal,**kwargs)
The signal parameter can be either a Signal instance or a list/tuple of Signal instances.

See an example below:-

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
 
@receiver(post_save,sender=User)
defprofile(sender,value,**kwargs):
                       instance.profile.save()
 
If you want to register the receiver function to several signals you have to do it like this:-

@receiver([post_save,post_delete],sender=User) 




Where we have to use Signals in Django ?

It’s important  to know the the place where we use the signals in the Django Project because if we implement it wrong place whole thing will create a big mess and it’s not good. Now , first listen and remember one thing we cannot use it in main django we have to create it in app in the Django project.

Read the  Django documentation basics and you all know where to put the signals inside your Django project. I have used it in the project and Iam showing it below:

your_app/signals.py:


from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
 
from cmdbox.your_app.models import Profile
 
@receiver(post_save,sender=User)
defprofile(sender,value,created,**kwargs):
               ifcreated:
                        Profile.objects.create(user=value)
 
@receiver(post_save,sender=User)
defsave_profile(sender,value,**kwargs):
                     value.profile.save()
 

your_app/app.py:


from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
 
classProfile(AppConfig):
           name='cmdbox.your_app'
           verbose_name=_('your_app')
 
def start(self):
          import cmdbox.your_app.signals

your_app/__init__.py:


config='cmdbox.your_app.apps.Profile'
 
In the example above, just importing the signals module inside the start() method will work because Iam using the @receiver() decorator. If you are connecting the receiver function using the connect() method, refer to the example below:

your_app/signals.py:



 from cmdbox.your_app.models import Profile
 
defprofile(sender,value,created,**kwargs):
              ifcreated:
                    Profile.objects.create(user=value)
 
defsave_profile(sender,value,**kwargs):
                 value.profile.save()

your_app/app.py:


from django.apps import AppConfig
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
 
from cmdbox.your_app.signals import profile,save_profile
 
classProfiles(AppConfig):
            name='cmdbox.your_app '
           verbose_name=_('your_app')
 
defstart(self):
           post_save.connect(profile,sender=User)
           post_save.connect(save_,sender=User)
 

your_app/__init__.py:


config='cmdbox.your_app.apps.=Config' 



Django Built-in Signals



Here you can find a list of some useful built-in signals. It is not complete, but those are the most common.


Model Signals
·     django.db.models.signals.pre_init:

                     receiver_function(sender,*args,**kwargs)
·     django.db.models.signals.post_init:

                    receiver_function(sender,instance)
·     django.db.models.signals.pre_save:

                                  receiver_function(sender,instance,raw,using,update_fields)
·    django.db.models.signals.post_save:

                   receiver_function(sender,instance,created,raw,using,update_fields)
·    django.db.models.signals.pre_delete:

                   receiver_function(sender,instance,using)
·    django.db.models.signals.post_delete:

                   receiver_function(sender,instance,using)
·   django.db.models.signals.m2m_changed:

             receiver_function(sender,instance,action,reverse,model,pk_set,using)

Request/Response Signals
·   django.core.signals.request_started:

                   receiver_function(sender,environ)
·  django.core.signals.request_finished:

                  receiver_function(sender,environ)
·  django.core.signals.got_request_exception:

                 receiver_function(sender,request)

If you want to read and learn more things about Django signals, https://docs.djangoproject.com/en/3.0/topics/signals/ to access the official docs.

If you Guy’s like this tutorial or if you all want solutions of some problems then comment here . . . . .

Reactions

Post a Comment

0 Comments