Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 9 · Django Forms & Validation
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/MethodTypeContains
is_valid()Method, returns boolTriggers validation, returns True/False
errorsDict-like objectField name -> list of error messages (populated after validation)
cleaned_dataDictField 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/MethodTypeContains
is_valid()Method, bool returnValidation trigger करता है
errorsDict-likeField name -> error messages
cleaned_dataDictValidated, 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)  # True

Was this answer clear?