Shatish Desai
Shatish Desai

Reputation: 605

Why we use cleaned_data on forms in django

Why we use cleaned_data firstname= form.cleaned_data.get("first_name")

What is the point in this and why is it necessary?

Upvotes: 3

Views: 2152

Answers (2)

Paul Munyao
Paul Munyao

Reputation: 195

When data has been submitted to the database through the forms, it has to be validated or the user has to be authenticated. When it's being returned to the user this is how it's being accessed name = form.cleaned_data['name']

here I've used just a name but one can also use an email When the data is returned it's returned in a more readable format.

Upvotes: 0

Sheraram_Prajapat
Sheraram_Prajapat

Reputation: 597

When you call is_valid() method on a form, it results in validation and cleaning of the form data. In the process, Django creates an attribute called cleaned_data , a dictionary which contains cleaned data only from the fields which have passed the validation tests.

There 2 are two types: basic Form (forms.Form) and ModelForm (forms.ModelForm).

If you are using a ModelForm then there is no any need of using a cleaned_data dictionary because when you do form.save() it's already be matched and the clean data is saved. But you are using basic Form then you have to manually match each cleaned_data to its database place and then save the instance to the database not the form.

For example basic Form:

if form.is_valid():
    ex = Example()
    ex.username = form.cleaned_data['username']
    ex.save()

For example ModelForm:

if form.is_valid():
    form.save()

IMPORTANT: If the form pass from is_valid() stage then there is no any unvalidated data.

Upvotes: 3

Related Questions