Built-in Validation
Part of the Forms section of Coddy's Django journey. Lesson 9 of 20.
An event needs a description and a number of places. Each form field checks its own kind of value, and its arguments add rules. You have met two: every field is required, and max_length=100 refuses a longer title.
min_valueon anIntegerField: refuses a smaller number.required=Falseon any field: it may be left empty.
A widget decides how a field is drawn: widget=forms.Textarea makes a large text box. A board game booking form:
class TableForm(forms.Form):
players = forms.IntegerField(min_value=2)
wishes = forms.CharField(widget=forms.Textarea, max_length=500)
phone = forms.CharField(required=False)An empty optional text field gives "" in cleaned_data; an empty optional number gives None. Your template's loop draws new fields with no change.
Challenge
EasyEvents get a description and a number of places.
- In
events/forms.py, adddescriptiontoEventForm: text in a large box, which may be left empty. Addcapacity: a whole number of at least 1. - In
new_event, save both on the event.
Add an event with capacity 25 and no description: its page shows 25 places.
Try it yourself
from django import forms
class EventForm(forms.Form):
title = forms.CharField(max_length=100)
date = forms.DateField()
place = forms.CharField(max_length=100)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Forms
2Django Forms
A Django FormDrawing a FormPractice on your own: Django playground