'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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sheraram_Prajapat |
| Solution 2 | Paul Munyao |
