Interview question
What is the difference between form.is_valid(), form.errors, and form.cleaned_data? form.is_valid(), form.errors, और form.cleaned_data में क्या अंतर है?
Answer
| Attribute/Method | Type | Contains |
|---|---|---|
| is_valid() | Method, returns bool | Triggers validation, returns True/False |
| errors | Dict-like object | Field name -> list of error messages (populated after validation) |
| cleaned_data | Dict | Field name -> validated, converted Python value (only if valid) |
form = BookForm(request.POST)
# is_valid() triggers the validation process and returns a boolean
if form.is_valid():
print('Form is valid')
# cleaned_data is ONLY reliable AFTER is_valid() returns True
title = form.cleaned_data['title'] # already validated and type-converted
price = form.cleaned_data['price'] # e.g. Decimal, not a raw string
else:
print('Form is invalid')
print(form.errors)
# {'title': ['This field is required.'], 'price': ['Enter a valid number.']}
# Accessing errors for a SPECIFIC field
if form.errors.get('title'):
print('Title errors:', form.errors['title'])
# as_json - errors can be serialized for AJAX responses
import json
errors_json = form.errors.as_json()
# IMPORTANT: cleaned_data only contains keys for fields that PASSED
# validation - if a field fails, it's missing from cleaned_data entirely
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'price']
form = BookForm({'title': '', 'price': 'not-a-number'})
form.is_valid() # False
print(form.cleaned_data) # {} - both fields failed, so nothing is present
# is_bound - distinguishes an unbound (blank) form from a bound (submitted) one
empty_form = BookForm()
print(empty_form.is_bound) # False - no data submitted yet
submitted_form = BookForm(request.POST)
print(submitted_form.is_bound) # True - data was provided| Attribute/Method | Type | Contains |
|---|---|---|
| is_valid() | Method, bool return | Validation trigger करता है |
| errors | Dict-like | Field name -> error messages |
| cleaned_data | Dict | Validated, converted values |
form = BookForm(request.POST)
if form.is_valid():
print('Form valid है')
title = form.cleaned_data['title']
price = form.cleaned_data['price']
else:
print('Form invalid है')
print(form.errors)
if form.errors.get('title'):
print('Title errors:', form.errors['title'])
import json
errors_json = form.errors.as_json()
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'price']
form = BookForm({'title': '', 'price': 'not-a-number'})
form.is_valid() # False
print(form.cleaned_data) # {} - दोनों fail हुए
empty_form = BookForm()
print(empty_form.is_bound) # False
submitted_form = BookForm(request.POST)
print(submitted_form.is_bound) # TrueWas this answer clear?