Django Signals
Tags: python, django
Published: 2021-01-05 20:36:21

# Django Signals:

Django has been into existence from quite some time now and it is one of the most popular frameworks for backend and REST API development, not only because it has a great developer community behind it but also because of so many cool and comprehensive features. Today, we’ll try and explore one of these features. While developing Python Backends or APIs there can be a lot of use case where we might need to take some event driven actions or complete some backend jobs. 

Let’s understand with an example, we all know that Django has its own very powerful ORM tool to manage database transactions. In some cases when we perform CRUD operations to a database table using Django models, we might need to perform some additional actions.  

So, if there is a model called Product, and it is associated with images. When we delete a product from the database, we need to delete images related to the product stored in the file system, we need to perform this action during the deletion operation. We can do this process in views. But to make your code follow clean code principles, Django provides us an elegant way to handle these situations. Django has concept - called **Signals**.

Django&#39;s signals are utilities that allow us to associate events with actions. We can develop a simple function that runs when a signal calls it. We use  **@receiver**  decorator for the receiver function for which we need to execute when specific signal is called.

## Django&#39;s built-in Signals:

Django provides a set of built-in signals that let user code get notified by Django itself of certain actions. These include some useful notifications:

-  **django.db.models.signals.pre\_save**  &amp;  **django.db.models.signals.post\_save** : Sent before or after a model&#39;s save() method is called
-  **django.db.models.signals.pre\_delete**  &amp;  **django.db.models.signals.post\_delete** : Sent before or after a model&#39;s delete() method or queryset&#39;s delete() method is called
-  **django.db.models.signals.m2m\_changed** : Sent when a ManyToManyField on a model is changed
-  **django.core.signals.request\_started**  &amp;  **django.core.signals.request\_finished** : Sent when Django starts or finishes an HTTP request

In this blog post we will implement **pre\_save** , **post\_save** and **pre\_delete** signal use cases.

## Arguments:

Most of the Django&#39;s signals sends 2 arguments to the signal receivers i.e

- **Sender:** The model class for which we are sending the signals
- **Instance:** The actual instance of the model that is being modified (Create, Update or Delete)

## Using post\_save:

Now in our example of Product model. Let&#39;s say if we want to send email notification for the user if any new product is created in the database. We can use **post\_save** signal for this purpose.

Along with the Sender, Instance arguments **post\_save** signal sends other user useful argument called created which is useful to understand if the object is being created or updated.

After writing the **post\_save** signal our models.py will look like the following.

![post_save](https://raw.githubusercontent.com/chaitu210/django_signal_screenshots/main/carbon.png)

## Using pre\_save:

Let&#39;s say if we want to send email notification for the user if any product price is dropped. We can use  **pre\_save**  signal for this purpose.

Here in this signal the instance holds the data that is not saved yet, so we can compare this data with the original record data and perform specific business actions.

After writing the  **pre\_save**  signal our models.py will look like the following.

![pre_save](https://raw.githubusercontent.com/chaitu210/django_signal_screenshots/main/carbon%20(1).png)

## Using pre\_delete:

In our current example let&#39;s say if there are any images associated with the product, we need to remove the images associated with the Product. So, we can use  **pre\_delete**  signal for this purpose.

After writing the **pre\_delete** signal our models.py will look like the following.

![pre_delete](https://raw.githubusercontent.com/chaitu210/django_signal_screenshots/main/carbon%20(2).png)

## Writing Custom Signal:

We can write our own Custom signals for the models. Let&#39;s say if we want to record the number of views that a product received, we can write our own signal, and using this signal we can record the User who viewed the Product and also update number of views that a product received.

To create a custom Signal, create a file called **signals.py** in your application.

**signals.py**

![signals](https://raw.githubusercontent.com//chaitu210/django_signal_screenshots/main/carbon%20(3).png)

To run the receiver function, we need to create **receivers.py** which contains the receiver function which will be called when the signal is dispatched. In receivers.py we need to connect the signal and receiver function.

**receivers.py**

![receivers](https://raw.githubusercontent.com/chaitu210/django_signal_screenshots/main/carbon%20(4).png)

In order to make the receiver function work when the custom signal is called, we need to make sure we import these receivers in the app config i.e in our apps.py

**apps.py**

![apps](https://raw.githubusercontent.com/chaitu210/django_signal_screenshots/main/carbon%20(5).png)

Now we are all set to use the signal. To use our custom signal, we use send method of the signal along with the Sender and Other arguments.

![signalcall](https://raw.githubusercontent.com/chaitu210/django_signal_screenshots/main/carbon%20(6).png)

To learn more about signals, [click here](https://docs.djangoproject.com/en/3.1/topics/signals/) to access official docs.

Disclaimer: This is a personal [blog, post, statement, opinion]. The views and opinions expressed here are only those of the author and do not represent those of any organization or any individual with whom the author may be associated, professionally or personally.