How to Override Form Data in the models.py File in Django



Python


In this article, we show how to override form data in the models.py file in Django.

There are specific times when you either need to overwrite data that a user has entered into a form or extract data from the user to enter into a form that is not even visible to the end user. This may be something such as the user's username that s/he is currently logged in.

Overwriting data can be done in a number of places in the Django project.

It can be done in models.py, admin.py, or views.py.

In this article, we show how to overwrite form data in the models.py file, which is file where a database is created. We use the save() method. Underneath the creation of the database table, we create a save method that is able to override data that a user enters in.


models.py File

In this example, we create a simple database table in the models.py file called Video. This Video model (or database table) has 4 fields: user, name, description, and videofile.

This is shown in the code below.



So you can see we have a basic model.

In this model (database table), we create 4 fields: user, name, description, and videofile.

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

We then create a save method(), passing self, *args, and **kwargs as parameters to this method.

The field, self.name references the name field. What we set this equal to overrides what the user has entered in to the name field of the form. So whatever the user has been completely erased and replaced with, "This is the new name"

self.description references the description field. What we set this equal to overrides what the user has entered in to the description field and replaces it with, "This is the new description"

We then save the changes we have made with the line, super(Video, self).save(*args, **kwargs)

Video gets replaced with the name of the database table you have created.

And this is all that is needed to override form data in the models.py file 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...