How to Execute a post_save Signal in Django



Python


In this article, we show how to execute a post_save signal in Django.

So, first thing, what is a post_save signal?

A post_save signal is a function that is carried out after a database table (model) is saved.

A post_save signal basically signals for a function to occur after the database table (model) is saved.

When would we want to use a post_save signal?

A post_save signal is used when you want to do some type of function or action after a database table (model) is saved.

Let's say you want to create a default photo for a user once a person has signed up on your website and have this stored in the database.

Each time a user is created, we want to automatically create a default photo and have this in a database table. The user can then later upload a photo of his or her choice.

This is a perfect situation of when you would use a post_save signal in Django.

Any time you want to use a function or perform an action after a certain model has been saved, you can use a post_save signal.

So now that you know what a post_save signal is and when to use it, let's go over an actual example in Django code. This will be quick.

In the following code below, a default photo is created for a user once a user has been created.



So this is a model that uses a post_save signal for the code field of the model.

So in order to use a post_save signal in Django, we must import post_save from django.db.models.signals

Basically, we define a post_save function, post_save_userphoto_model_receiver()

This function will create a UserPhoto object for a user once the user is created. Notice that the function contains the line, if created:, which will only create a UserPhoto object if the user is created, not just if the User is saved. So post_save signals do not need to be executed every time an object of a particular model is saved, if you put conditions in the post_save function.

So we created the function but we haven't connected it to the post_save signal mechanism.

So we do this using the line, post_save.connect(post_save_userphoto_model_receiver, sender= settings.AUTH_USER_MODEL)

The sender is the model you are dealing with. We're saying that after the User is created, we want to run the post_save function and create a UserPhoto model if the user is created.

And this is all that is required to execute a post_save signal in Django.

Again, a post_save signal is a signal that calls for a function to be executed after the model is saved. It is used often when you want to transfer data from one model to another or create another model, or simply do anything after it's saved.

And this is how to execute a post_save signal in Django.


Related Resources

How to Execute a pre_save Signal in Django



HTML Comment Box is loading comments...