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.

  • forms.IntegerField(min_value=1, max_value=5): a whole number between the limits.
  • forms.EmailField(): refuses text that is not an email address.
  • 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 product review form:

class ReviewForm(forms.Form):
    stars = forms.IntegerField(min_value=1, max_value=5)
    comment = forms.CharField(widget=forms.Textarea, max_length=500)
    nickname = 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

Add two fields to EventForm:

  • description: text in a large box, which may be left empty.
  • capacity: a whole number of at least 1.

In new_event, save both on the event. Press Run and open /events/new/.

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