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
Easy- In
events/forms.py, writeEventForm:titleandplaceas text of at most 100 characters,dateas a date. - In
new_event, check the POST with it. If valid, create the event from the converted values and redirect. If not, render the page witherrorset toPlease check the form.
Press Run and send the form with no date.
Try it yourself
from django import forms
All lessons in Forms
Practice on your own: Django playground