ExamHoot

Understanding Django Form Validation Pipeline and Custom Validators

from django import forms
from django.core.exceptions import ValidationError

class UserRegistrationForm(forms.Form):
    email = forms.EmailField()
    age = forms.IntegerField()
    
    def clean_age(self):
        age = self.cleaned_data.get('age')
        if age < 18:
            raise ValidationError('Age must be at least 18')
        return age
    
    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        age = cleaned_data.get('age')
        if email and age and age > 65:
            raise ValidationError('Senior citizens cannot register')
        return cleaned_data

form = UserRegistrationForm(data={'email': 'hari@example.com', 'age': '70'})
print(form.is_valid())
  1. True, because the email field is valid

  2. False, because the cross-field validation in clean() rejects users over 65

  3. True, because clean_age() only checks if age >= 18

  4. An exception is raised and the program crashes

Show answer & explanation

Correct answer

False, because the cross-field validation in clean() rejects users over 65

Explanation

The clean() method performs cross-field validation after individual field validation. Since Hari is 70 years old, the clean() method raises a ValidationError preventing form validation from succeeding. The output is False.

Written by ExamHoot EditorialPublished · Updated

All 30 Django Forms and Validation questions

  1. 1.What is the primary purpose of Django Forms?
  2. 2.Which Django class is used to create a form?
  3. 3.What does the is_valid() method do in Django Forms?
  4. 4.Which field type in Django Forms is used for email validation?
  5. 5.What is the purpose of the clean() method in Django Forms?
  6. 6.How do you access form errors in Django?
  7. 7.What does ModelForm do in Django?
  8. 8.Which method is used to render form fields in a Django template?
  9. 9.What is the purpose of the required parameter in Django form fields?
  10. 10.Which validator ensures a field value is within a specific range?
  11. 11.Scenario:
  12. 12.What will be the output of the following Django form code?
  13. 13.Scenario:
  14. 14.What will be the output of the following code?
  15. 15.Scenario:
  16. 16.What will this code output?
  17. 17.Scenario:
  18. 18.What will be the output of the following ModelForm code?
  19. 19.Scenario:
  20. 20.What will this code output?
  21. 21.Understanding Django Form Validation Pipeline and Custom Validators
  22. 22.Django ModelForm Field Exclusion and Customization
  23. 23.Scenario:
  24. 24.Django Form Rendering with Widgets and HTML Attributes
  25. 25.Understanding Form.errors and Non-Field Errors
  26. 26.Django Form Inheritance and Method Resolution Order
  27. 27.Scenario:
  28. 28.Working with Form Bound and Unbound States
  29. 29.Custom Validators and Reusability Across Forms
  30. 30.Scenario: