Forms and User Input
Lesson 8: Forms and User Input
In this lesson, we will learn how to create forms and handle user input in Django applications. Forms are essential for collecting data from users and can be used for various tasks such as user registration, feedback, and data submission.
Understanding Django Forms
Django provides a powerful form handling library that simplifies the process of creating forms and validating user input. The primary components of Django forms are:
- Form Class: This is where you define the fields and validation rules for your form.
- Rendering Forms: This involves displaying the form on a web page using Django templates.
- Handling Form Submission: This is the process of validating and processing the data submitted by the user.
Creating a Simple Form
Let's create a simple contact form that collects a user's name and email address.
Step 1: Create a Form Class
Create a new file called forms.py in your Django app directory and add the following code:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label='Your Name', max_length=100)
email = forms.EmailField(label='Your Email')
Step 2: Create a View to Handle the Form
Next, we will create a view that will render the form and handle the submission. Update your views.py file:
from django.shortcuts import render
from .forms import ContactForm
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the data in form.cleaned_data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
# Here you can send an email, save to the database, etc.
return render(request, 'thank_you.html', {'name': name})
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Step 3: Create Templates
Create a template for the contact form called contact.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
And create a simple thank_you.html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thank You</title>
</head>
<body>
<h1>Thank You, {{ name }}!</h1>
<p>Your message has been received.</p>
</body>
</html>
Step 4: Update URL Patterns
Finally, update your urls.py to include the new contact view:
from django.urls import path
from .views import contact_view
urlpatterns = [
path('contact/', contact_view, name='contact'),
]
Best Practices
- Validation: Always validate user input to prevent malicious data from being processed.
- CSRF Protection: Use
{% csrf_token %}in your forms to protect against Cross-Site Request Forgery attacks. - User Feedback: Provide clear feedback to users upon successful submission or errors in the form.
Common Mistakes: - Forgetting to include
{% csrf_token %}in forms, which can lead to security vulnerabilities. - Not checkingform.is_valid()before processing the data.
Summary
- Django forms simplify user input handling and validation.
- Create a form class to define fields and validation rules.
- Use views to render forms and handle submissions.
- Always validate and sanitize user input for security.
Exercises
Exercise 1: Create a Registration Form
- Create a new form class for user registration with fields for username, password, and email.
- Create a view to handle the registration form and display a success message.
Exercise 2: Add Validation
- Add custom validation to the email field to ensure it belongs to a specific domain (e.g., example.com).
Exercise 3: Style Your Form
- Use CSS to style your
contact.htmlform to make it visually appealing.
Summary
- Django forms are used to collect and validate user input.
- Create a form class to define the structure of your forms.
- Use views to process form submissions and provide user feedback.
- Always implement security measures like CSRF protection.