Bird
Raised Fist0
Djangoframework~20 mins

Testing forms in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Form Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Django form validation?
Consider this Django form code snippet. What will form.is_valid() return if the input data is {'name': '', 'age': '25'}?
Django
from django import forms

class PersonForm(forms.Form):
    name = forms.CharField(required=True)
    age = forms.IntegerField(required=True)

form = PersonForm({'name': '', 'age': '25'})
valid = form.is_valid()
Afalse
Btrue
CRaises ValidationError
Dnull
Attempts:
2 left
💡 Hint
Think about what happens when a required CharField is empty.
state_output
intermediate
2:00remaining
What error message does this form produce for invalid email?
Given this Django form, what error message will appear if the email input is 'invalid-email'?
Django
from django import forms

class EmailForm(forms.Form):
    email = forms.EmailField()

form = EmailForm({'email': 'invalid-email'})
form.is_valid()
errors = form.errors['email']
A['Invalid input format.']
B['This field is required.']
C['Enter a valid email address.']
D['Email must contain @ symbol.']
Attempts:
2 left
💡 Hint
Django's EmailField has a built-in validator with a standard message.
📝 Syntax
advanced
2:30remaining
Which option correctly overrides the clean method in a Django form?
You want to add custom validation to a Django form by overriding the clean method. Which code snippet is correct?
Django
from django import forms

class MyForm(forms.Form):
    age = forms.IntegerField()

    def clean(self):
        # custom validation here
        pass
Adef clean(self):\n cleaned_data = self.clean()\n if cleaned_data['age'] < 18:\n raise forms.ValidationError('Must be at least 18.')\n return cleaned_data
Bdef clean(self):\n age = self.cleaned_data['age']\n if age < 18:\n raise forms.ValidationError('Must be at least 18.')
Cdef clean(self):\n cleaned_data = super().clean()\n if cleaned_data['age'] < 18:\n self.add_error('age', 'Must be at least 18.')\n return cleaned_data
Ddef clean(self):\n cleaned_data = super().clean()\n age = cleaned_data.get('age')\n if age and age < 18:\n raise forms.ValidationError('Must be at least 18.')\n return cleaned_data
Attempts:
2 left
💡 Hint
Remember to call super().clean() to get cleaned_data and return it.
🔧 Debug
advanced
2:30remaining
Why does this form validation always fail?
This Django form always fails validation even with valid data. What is the cause?
Django
from django import forms

class SampleForm(forms.Form):
    name = forms.CharField()

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name.isalpha():
            raise forms.ValidationError('Only letters allowed.')
        # Missing return statement here

form = SampleForm({'name': 'Alice'})
valid = form.is_valid()
Aclean_name method does not return the cleaned value, causing validation to fail.
BThe ValidationError message is incorrect and causes failure.
CThe form data dictionary keys must be bytes, not strings.
DThe name field is missing required=true, so validation fails.
Attempts:
2 left
💡 Hint
Check the clean_name method's return behavior.
🧠 Conceptual
expert
3:00remaining
What is the effect of calling form.full_clean() twice in Django?
In Django forms, what happens if you call form.full_clean() two times in a row on the same form instance?
Django
from django import forms

class TestForm(forms.Form):
    field = forms.CharField()

form = TestForm({'field': 'value'})
form.full_clean()
form.full_clean()
AThe second call does nothing because the form is already cleaned.
BThe form is cleaned again, resetting errors and cleaned_data.
CRaises an exception because full_clean should be called only once.
DThe second call appends errors to the existing errors without clearing.
Attempts:
2 left
💡 Hint
Consider what full_clean does internally each time it runs.

Practice

(1/5)
1. What does the form.is_valid() method do in Django form testing?
easy
A. Checks if the form data meets all validation rules
B. Saves the form data to the database
C. Clears all data from the form
D. Returns the form's HTML code

Solution

  1. Step 1: Understand the purpose of form.is_valid()

    This method runs all validation checks on the form data to ensure it meets the rules defined in the form fields.
  2. Step 2: Identify what form.is_valid() returns

    It returns True if all data is valid, otherwise False. It does not save or clear data.
  3. Final Answer:

    Checks if the form data meets all validation rules -> Option A
  4. Quick Check:

    Validation check = A [OK]
Hint: Remember: is_valid() checks data correctness, not saving [OK]
Common Mistakes:
  • Thinking is_valid() saves data
  • Confusing is_valid() with form rendering
  • Assuming is_valid() clears form data
2. Which of the following is the correct way to create a form instance with POST data in a Django test?
easy
A. form = MyForm(request.GET)
B. form = MyForm(data=request.GET)
C. form = MyForm()
D. form = MyForm(request.POST)

Solution

  1. Step 1: Recall how to instantiate a form with POST data

    In Django, you pass POST data directly as the first argument to the form constructor, like MyForm(request.POST).
  2. Step 2: Evaluate each option

    form = MyForm(request.GET) uses GET data, which is incorrect for POST forms. form = MyForm(data=request.GET) uses GET data with keyword argument data=, incorrect for POST. form = MyForm(request.POST) correctly passes request.POST as the first argument. form = MyForm() creates an empty form without data.
  3. Final Answer:

    form = MyForm(request.POST) -> Option D
  4. Quick Check:

    Form with POST data = C [OK]
Hint: Pass POST data as first argument: MyForm(request.POST) [OK]
Common Mistakes:
  • Using GET data instead of POST
  • Forgetting to pass data to the form
  • Using incorrect keyword arguments
3. Given the following form test code, what will print(form.errors) output if the 'email' field is missing?
data = {'name': 'Alice'}
form = ContactForm(data)
form.is_valid()
print(form.errors)
medium
A. {'email': ['This field is required.']}
B. {}
C. {'name': ['Invalid input.']}
D. None

Solution

  1. Step 1: Understand form validation with missing required fields

    If a required field like 'email' is missing, form.is_valid() returns False and form.errors contains an error message for that field.
  2. Step 2: Analyze the error output

    The error dictionary will have a key 'email' with a list containing the message 'This field is required.' since 'email' was not provided.
  3. Final Answer:

    {'email': ['This field is required.']} -> Option A
  4. Quick Check:

    Missing required field error = D [OK]
Hint: Missing required field shows error in form.errors [OK]
Common Mistakes:
  • Expecting empty errors when required field missing
  • Confusing error keys with field names
  • Assuming errors is None instead of a dict
4. Identify the error in this Django form test snippet:
form = MyForm()
form.is_valid()
print(form.errors)

Why might form.errors always be empty here?
medium
A. form.errors only shows errors after saving
B. is_valid() was not called before accessing errors
C. Form was not given any data to validate
D. MyForm has no fields defined

Solution

  1. Step 1: Check how the form instance is created

    The form is created without passing any data, so it has no input to validate.
  2. Step 2: Understand why errors are empty

    Without data, form.is_valid() returns False but form.errors is empty because no fields were checked against input data.
  3. Final Answer:

    Form was not given any data to validate -> Option C
  4. Quick Check:

    No data means no validation errors = A [OK]
Hint: Always pass data to form to test validation errors [OK]
Common Mistakes:
  • Assuming errors appear without data
  • Forgetting to call is_valid() before errors
  • Thinking errors require saving form
5. You want to test a Django form that has a custom clean method rejecting empty 'username' and a password confirmation field. Which test approach correctly checks both validations?
hard
A. Submit data with valid 'username' and matching passwords, then check form.errors is empty
B. Submit data with empty 'username' and mismatched passwords, then check form.errors for both fields
C. Submit data with empty 'username' only, ignoring password fields
D. Submit data with mismatched passwords only, ignoring 'username'

Solution

  1. Step 1: Understand the form validations

    The form has two validations: a custom clean method that rejects empty 'username' and a password confirmation check.
  2. Step 2: Design a test that triggers both errors

    To test both, submit data with an empty 'username' and mismatched passwords, then call form.is_valid() and check form.errors contains errors for both fields.
  3. Final Answer:

    Submit data with empty 'username' and mismatched passwords, then check form.errors for both fields -> Option B
  4. Quick Check:

    Test all validations with bad data = B [OK]
Hint: Test all validations by submitting data that breaks each rule [OK]
Common Mistakes:
  • Testing only one validation at a time
  • Ignoring password confirmation in tests
  • Assuming valid data tests validation errors