Menu
CoddyTech

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 icon

Challenge

Easy

Let a Django form check the new event.

  1. In events/forms.py, write EventForm: title and place as text up to 100 characters, date as a date.
  2. In new_event, build the form from request.POST. If it is valid, create the event from form.cleaned_data and redirect to it. If not, set error to Please 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