Form handling with class-based views
Form processing generally has 3 paths:
- Initial
GET
(blank or prepopulated form) POST
with invalid data (typically redisplay form with errors)POST
with valid data (process the data and typically redirect)
Implementing this yourself often results in a lot of repeated boilerplate code (see Using a form in a view). To help avoid this, Django provides a collection of generic class-based views for form processing.
Basic forms
Given a simple contact form:
# forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField() message = forms.CharField(widget=forms.Textarea) def send_email(self): # send email using the self.cleaned_data dictionary pass
The view can be constructed using a FormView
:
# views.py ...
Get Mastering Django: Core now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.