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



Python


In this article, we show how to override form data in the views.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 views.py file, which is probably the most dynamic place to do, because you have to access to every type of variable, including the request object.


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.


views.py File

So in the views.py file below, we are going to overwrite the name field of the Video model, as well as the description and user fields.

This is shown in the code below.



So let's go over this views.py file now.

So in this views.py file, we import the Video database table from hte models.py file.

We then create the function-based view, videos, passing in request as its parameter (which is always needed).

We then get all of the objects (videos) from the Video database table, with the line, allvideos= Video.objects.all()

We then create the variable form and set it equal to, VideoForm(request.POST or None, request.FILES or None)

We then check to see if this form data is valid, using the form.is_valid() function.

We then create the variable, fs and set it equal to, fo

You can name this variable anything. I named it fs for file save.

We set fs equal to, form.save(commit=False)

We then can use this fs variable to rewrite form fields.

fs.field_name references the field of the table specified for field_name

We overwrite the name field to "New name", using the line, fs.name= "New name"

This means that whatever a user entered into the name field has been completely erased and replaced with "New name"

We rewrite the description using the line, fs.description= "New description"

And we set the user to the user currently logged in and who submitted the form data using the line, fs.user= request.user

We then save the changes using the line, fs.save()

We then pass the form and allvideos variable into the context dictionary and then pass the context dictionary into the templates file, videos.html.

And this is all that is required to override and overwrite form data that a user has submitted in the views.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...