How to Override Form Data in Django Using the post_save Method 


               


How to Override Form Data in Django Using the post_save Method



Python


In this article, we show how to override form data in Django using the post_save method.

Django provides a built-in post_save method that we can import into a file to save data after the form data has been saved.

In certain circumstances, this may be necessary.

In this article, we go through an example of overriding form data in Django using the post_save method.


models.py File

So below, we create a database called Video that has 4 fields and then we override the name and description form data fields using the post_save method.



So the post_save method is usually run in the models.py file.

Before we can use the post_save method, we must import it. We do so through the following line, from django.db.models.signals import post_save

If you are also going to use the pre_save method, you would import it by the following line, from django.db.models.signals import pre_save, post_save

The immediate above line imports both.

So we create one underneath the database table creation.

So we first build a model named Video that has 4 fields, user, name, description, and videofile.

We then have an __str__ method so that a generic object isn't returned when we reference an object.

We then create our post_save_videos function.

This function takes in a number of parameters, including sender, instance, created, *args, and **kwargs. *args and **kwargs are passed in just to cover all ways a user can specify information when calling this method. *args is just like a regular variable. And **kwargs is a key=value pair.

We then are able to access a field through the instance.field statement.

instance.name references the name field of the database table. We set this equal to, "This is the new name". So whatever what was in the name field has been completely erased and replaced with, "This is the new name"

instance.description refers to the description field of the database table. We set this equal to "This is new description", which erases what was in the description field and replaces it with, "This is the new description"

We then save the changes we have made with the line, instance.save()

Now we must call the method in order to actually run the code. This is done through the line, post_save.connect(post_save_videos, sender=Video)

post_save_videos is the method we created and then in the second parameter we specify the database table, which in this case is Video.

With this code, we are able to override form data with the post_save method in Django.


Related Resources

How to Create a Video Uploader with Python in Django

How to Create an Image Uploader with Python in Django



HTML Comment Box is loading comments...