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.
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:
Let's create a simple contact form that collects a user's name and email address.
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')
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})
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>
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'),
]
{% csrf_token %} in your forms to protect against Cross-Site Request Forgery attacks.Common Mistakes: - Forgetting to include
{% csrf_token %}in forms, which can lead to security vulnerabilities. - Not checkingform.is_valid()before processing the data.
contact.html form to make it visually appealing.