Menu
CoddyTech

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_value on an IntegerField: refuses a smaller number.
  • required=False on 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 icon

Challenge

Easy

Events get a description and a number of places.

  1. In events/forms.py, add description to EventForm: text in a large box, which may be left empty. Add capacity: a whole number of at least 1.
  2. 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Forms

Practice on your own: Django playground