0
0
Djangoframework~30 mins

Why Django forms matter - See It in Action

Choose your learning style9 modes available
Why Django forms matter
📖 Scenario: You are building a simple website where users can submit their contact information. You want to collect their name and email safely and easily.
🎯 Goal: Build a Django form to collect user name and email, and show how Django forms help handle user input securely and cleanly.
📋 What You'll Learn
Create a Django form class with fields for name and email
Add a configuration variable for maximum length of the name
Use the form in a Django view to process submitted data
Render the form in a Django template with proper HTML
💡 Why This Matters
🌍 Real World
Collecting user input safely is essential for websites like contact pages, sign-ups, and surveys.
💼 Career
Understanding Django forms is important for backend web developers to build secure and user-friendly web applications.
Progress0 / 4 steps
1
Create the Django 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. Use forms.CharField() for name and forms.EmailField() for email.

2
Add a max length configuration
Add a variable called MAX_NAME_LENGTH set to 50. Then update the name field in ContactForm to use max_length=MAX_NAME_LENGTH.
Django
Need a hint?

Define MAX_NAME_LENGTH before the form class. Use it as the max_length argument in CharField.

3
Use the form in a Django view
Create a Django view function called contact_view that imports ContactForm. Inside the function, instantiate form = ContactForm(request.POST or None). Then check if form.is_valid() and if so, assign name = form.cleaned_data['name'] and email = form.cleaned_data['email'].
Django
Need a hint?

Use request.POST or None to instantiate the form. Use form.is_valid() to check data. Access cleaned data with form.cleaned_data['fieldname'].

4
Render the form in a Django template
Write the HTML code for a template named contact.html that renders the form using {{ form.as_p }} inside a <form> tag with method post. Add the CSRF token with {% csrf_token %} inside the form.
Django
Need a hint?

Use <form method="post">. Add {% csrf_token %} for security. Render the form fields with {{ form.as_p }}. Add a submit button.