0
0
Djangoframework~30 mins

Testing forms in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing forms
📖 Scenario: You are building a simple Django web app with a form for users to submit their name and email. You want to write tests to check that the form works correctly.
🎯 Goal: Write Django form tests step-by-step to verify the form validates input and saves data properly.
📋 What You'll Learn
Create a Django form class with fields name and email
Add a test case class to test the form
Write a test to check the form is valid with correct data
Write a test to check the form is invalid with missing data
💡 Why This Matters
🌍 Real World
Forms are common in web apps for user input. Testing forms ensures users cannot submit wrong or incomplete data.
💼 Career
Django developers often write form tests to maintain app quality and prevent bugs in user input handling.
Progress0 / 4 steps
1
Create the form class
Create a Django form class called ContactForm with two fields: name as a CharField and email as an EmailField.
Django
Need a hint?

Use forms.Form as the base class. Define name and email as form fields.

2
Set up the test case class
Create a Django test case class called ContactFormTest that inherits from django.test.TestCase.
Django
Need a hint?

Import TestCase from django.test. Define an empty test class for now.

3
Write a test for valid form data
Inside ContactFormTest, write a test method called test_form_valid_data that creates a ContactForm with valid name and email data and asserts the form is valid using form.is_valid().
Django
Need a hint?

Create the form with a dictionary of valid data. Use self.assertTrue to check validity.

4
Write a test for invalid form data
Inside ContactFormTest, write a test method called test_form_invalid_data that creates a ContactForm with missing email and asserts the form is invalid using form.is_valid().
Django
Need a hint?

Create the form with missing email. Use self.assertFalse to check it is invalid.