from django import forms
from django.core.exceptions import ValidationError
def validate_even_number(value):
if value % 2 != 0:
raise ValidationError('This number must be even')
class MathForm(forms.Form):
number1 = forms.IntegerField(validators=[validate_even_number])
number2 = forms.IntegerField(validators=[validate_even_number])
form = MathForm(data={'number1': '4', 'number2': '7'})
print(form.is_valid())
print(form.errors)Custom Validators and Reusability Across Forms
True, because number1 is even
False, because number2 fails the even number validation
True, because custom validators are optional
An error is raised when applying multiple validators to a field
Show answer & explanationAnswer
Correct answer
False, because number2 fails the even number validation
Explanation
Custom validators are reusable functions that can be applied to multiple fields. Here, validate_even_number is applied to both number1 and number2. Since number2 is 7 (odd), validation fails. The form is invalid and errors contain the validation message for number2.
Written by ExamHoot EditorialPublished · Updated
All 30 Django Forms and Validation questions
- 1.What is the primary purpose of Django Forms?
- 2.Which Django class is used to create a form?
- 3.What does the is_valid() method do in Django Forms?
- 4.Which field type in Django Forms is used for email validation?
- 5.What is the purpose of the clean() method in Django Forms?
- 6.How do you access form errors in Django?
- 7.What does ModelForm do in Django?
- 8.Which method is used to render form fields in a Django template?
- 9.What is the purpose of the required parameter in Django form fields?
- 10.Which validator ensures a field value is within a specific range?
- 11.Scenario:
- 12.What will be the output of the following Django form code?
- 13.Scenario:
- 14.What will be the output of the following code?
- 15.Scenario:
- 16.What will this code output?
- 17.Scenario:
- 18.What will be the output of the following ModelForm code?
- 19.Scenario:
- 20.What will this code output?
- 21.Understanding Django Form Validation Pipeline and Custom Validators
- 22.Django ModelForm Field Exclusion and Customization
- 23.Scenario:
- 24.Django Form Rendering with Widgets and HTML Attributes
- 25.Understanding Form.errors and Non-Field Errors
- 26.Django Form Inheritance and Method Resolution Order
- 27.Scenario:
- 28.Working with Form Bound and Unbound States
- 29.Custom Validators and Reusability Across Forms
- 30.Scenario:
