In this article, we discuss what are signals in Django and how we can use them in our project.
Django includes a “signal dispatcher” which helps allow decoupled applications to get notified when actions occur elsewhere in the framework. 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. (from official Django doc)
In simple words, a signal is an object corresponding to a particular event, which means the Django signal allows certain senders to notify a set of receivers that some action has taken place.
Built-in Signals
Django provides some default signals. Now let’s understand the built-in signals in Django. Some of the most used signals are pre_save/post_save, pre_delete/post_delete, and pre_init/post_init.
- pre_save – Sent before a model save() method is called
- post_save – Sent after a model save() method is called
- pre_delete – Sent before a model’s delete() method is called
- post_delete – Send before a model’s delete() method is called
- pre_init – Send before instantiating a model init_() method
- post_init – Send after instantiating a model init_() method
- m2m_changed – Send when ManyToManyField changed on a model instance
Signals are used to perform some actions on or before the modification of a model instance. We can develop a function that will run when a signal calls it. In other words, signals are used to perform some action on the modification/creation of a particular entry in the database. For example, one who creates a profile instance, as soon as a new user instance is created in the database.
Arguments in signals
Now let’s understand the built-in signals in Django.
- receiver – The function that receives the signal and does something
- sender – Sends the signal
- created – Checks whether the model is created on not
- instance – Created model instance
- **kwargs – Wildcard keyword arguments
Where should I write signals?
We can create our signal in models.py or write a separate signals.py file and connect them with the signals in the apps.py file of our app.
my_app/signals.py:
def my_signal_name(sender, instance, created, **kwargs): #my code
my_app/signals.py:
from django.apps import AppConfig from django.db.models.signals import post_save from my_app.signals import my_signal_name class AppConfig(AppConfig): name = 'my_app' def ready(self): my_model = self.get_model('Mymodel') post_save.connect(my_signal_name, sender=my_model)
At the end
Django signals are a great way to communicate between your apps. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. If you go more please go through the official Django doc.