is_valid() method and cleaned_data attribute

16 views
Skip to first unread message

omar ahmed

unread,
Mar 22, 2019, 2:13:03 PM3/22/19
to Django users
hello guys
i created contact form
in my view :
if form.is_valid():
message = form.cleaned_data['message']
what is .is_valid() method and what is cleaned_data attribute ???

Marcio Bernardes

unread,
Mar 22, 2019, 3:33:56 PM3/22/19
to Django users
is_valid() validates the form, for instance, if you have a field for integers and the user passes a str the 'is_valid()' will return false. The cleaned_data is the method you can use to access the data from the input if the form is valid, if the form is not valid this method will not contain the invalid data, ref: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data

Mohammad Etemaddar

unread,
Mar 22, 2019, 3:37:25 PM3/22/19
to Django users
Every field in Form has validators which check the value against their conditions.
The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid

as you see there it checks if the form is bound and not has errors.

If you see errors, it's a method with attribute decorator. that triggers the full_clean( ) method.
full_clean does _clean_fields which populates the cleaned_data with validation checked data.

So, If you call the is_valid() and it returns True, You know that all form validators are applied to the data and it had no errors. also the cleaned_data is ready to use.
Reply all
Reply to author
Forward
0 new messages