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
form.cleaned_data
returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects.
form.data
returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
In my forms.py
I have two fields:
class Loginform(forms.Form):
username=forms.CharField()
password=forms.CharField(widget=forms.PasswordInput)
and in my views.py
:
def login_page(request):
form=Loginform(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
The above code prints the following output:
{'username': 'xyz', 'password': 'shinchan'}
If instead views.py
contains:
def login_page(request):
form=Loginform(request.POST or None)
if form.is_valid():
print(form)
The above code prints the following:
<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="xyz" required id="id_username"></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" required id="id_password"></td></tr>