Signal is one of the useful feature provided by Django, so let's talk about it.
- What is Signal
- How to use Built-in Signal
- How to create a custom one
What is Signal
Yes, it is the same as you are thinking, as its name suggests "Signal" gives notification to a sender at a specific event.
Let's say you want to get notified every time a guest visited your house.
You can set up a doorbell which will give you a signal that someone has arrived.
Django Signals works in the same manner whenever some event happens it sends a signal to do some defined task.
So you can use Signal when many codes are interested in a particular event.
There are awesome Built-in signals available which you can easily use.
Let's say I want to do something before an instance saved in my Post model.
First of all, I will create a Post model and then import a signal i.e. "pre_save"
- My models.py files will look like this -
from django.db import models from django.db.models.signals import pre_save,post_save #Inbuilt Signals # Create your models here. class Post(models.Model): title = models.CharField(max_length=30) def __str__(self): return self.title def save_post(sender,instance,**kwargs): print("Pre save") pre_save.connect(save_post,sender=Post) # This will trigger after the saving data into Post model
So when I save something in Post model I get the message "Pre Save"
Similarly you can do something after saving an instance using post_save signals.
Here is the list for all Built-in Django Signals
There is another famous one request_finished which you can use after a request is finished.
So far so good but how we can create a custom one.
wherever you want to use signals you have to import signals and receiver.
Then create an object of Signals class and then define a sender and receiver.
- views.py file
from django.shortcuts import render,HttpResponse from django.core.signals import request_finished from django.dispatch import receiver,Signal from .models import Post # Create your views here. time_stamp = Signal(providing_args=['timestamp']) def home(request): time_stamp.send(sender=None,timestamp="30/05/2021") return HttpResponse("Home Page") ## Custom Signal @receiver(time_stamp) def own_track(sender,**kwargs): print(kwargs)
So, if you have any suggestions or feedback let me know in the comment.
Thanks for reading.
Cover Image - Photo by Chinh Le Duc on Unsplash
Top comments (3)
epic tutorial dude!