How to Retain Values in Form Fields in Django Forms



Python


In this article, we show how to retain values in form fields of Django forms.

What is meant by this is that after a user has entered data into forms fields of a form and clicks the 'Submit' button, you want the data retained in the form.

This is usually the case when the data is contained to the same page, such as with online calculators, etc.

And this easily done in Django.

Basically you create your form, usually in a forms.py file with the app. Let's say we created a form called CustomerInformation (the forms.py file is normally where all forms of the app are kept).

Normally, we then import this form into the views.py file. In this file is how we can retain the data from the form.

So, once you have imported the form from the forms.py file, you can then assign the form to a variable and process it.

It is at this point where we specify the data be retained with request.POST or None passed into the form.

So, with the CustomerInformation form assign to the variable form, the line would be, form= CustomerInformation(request.POST or None)

This allows us to retain the data in the form fields of the form.

We show all the full code below.


forms.py File

Below is the code of the forms.py file.



So we have a form called CustomerInformation that has a first name, last name and email field.

Now let's go to the views.py file to see how to retain data on this form after a user fills out the fields and clicks the 'Submit' button.


view.py File

The code in the views.py file is as below.

So we first import the form from the forms.py file. We import the form, CustomerInformation. Then, in our function, when we're assigning the form to a variable (in this case, the variable is form), we pass into the form, request.POST or None.

What this line does is it retains data in the form fields when a user fills in the form fields and clicks the 'Submit' button.

Specifically, request.POST does this.

What or None does is it won't raise validation errors when the page initially loads. You want the user to actually click the 'Submit' button before all these validation errors are given. Or None makes sure that validation warnings aren't given to a user before the user clicks the Submit button.

So this is all that is needed to retain data in form fields of a form with Django forms (the Django form class).


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...