Django says if form.is_valid()
is True
. form.cleaned_data
is where all validated fields are stored. But I am confused about using the cleaned_data
function.
form.cleaned_data['f1']
-- cleaned data
request.POST.get('f1')
-- un-validated data
I have a model form in Django.
if form1.is_valid():
form1.save()
Does this save cleaned_data to the model or does it save unvalidated data.
form2=form1.save(commit=False);
Does form2 contain form1's cleaned_data or unvalidated data.
Apart from converting any date to python datetime object, is there a good example of benefit of using cleaned_data vs unvalidated data. Thanks
There 2 situations: using basic Form (forms.Form) and ModelForm (forms.ModelForm).
If you are using a ModelForm then there is no any need of playing with a cleaned_data
dictionary because when you do form.save()
it is 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()
NOTE: If the form pass from is_valid()
stage then there is no any unvalidated data.