A Django Form
Part of the Forms section of Coddy's Django journey. Lesson 5 of 20.
Send the form with no date and the site crashes: Django cannot turn empty text into a date. Checking each field by hand would take code for every field and every mistake.
A Django form describes the fields once, in forms.py, and each field knows what it accepts. A restaurant's booking form:
from django import forms
class BookingForm(forms.Form):
name = forms.CharField(max_length=50)
day = forms.DateField()
guests = forms.IntegerField()Every field is required unless you say otherwise, and a CharField strips spaces first, so a name of only spaces counts as empty.
In the view, build the form from what arrived and call is_valid(): it checks every field and returns True or False. Then form.cleaned_data holds the values converted to Python, so cleaned_data["day"] is a datetime.date, not text:
form = BookingForm(request.POST)
if form.is_valid():
day = form.cleaned_data["day"]Challenge
EasyLet a Django form check the new event.
- In
events/forms.py, writeEventForm:titleandplaceas text up to 100 characters,dateas a date. - In
new_event, build the form fromrequest.POST. If it is valid, create the event fromform.cleaned_dataand redirect to it. If not, seterrortoPlease check the form.
Send the form without a date: you see Please check the form.
Try it yourself
from django import forms
All lessons in Forms
Practice on your own: Django playground