Menu
CoddyTech

Checking One Field

Part of the Forms section of Coddy's Django journey. Lesson 10 of 20.

The board takes events dated last year. The built-in rules know types and limits, not your site. A rule of your own about one field goes in a method named clean_ plus the field's name. A sign-up form that keeps the name admin for the staff:

class SignupForm(forms.Form):
    username = forms.CharField(max_length=30)

    def clean_username(self):
        username = self.cleaned_data["username"]
        if username.lower() == "admin":
            raise forms.ValidationError("That name is reserved.")
        return username

is_valid() calls it after the field's own checks, so the value is already converted: a DateField gives a date. Raising forms.ValidationError refuses the field, and the message appears under it.

The method must return the value: what it returns lands in cleaned_data. Without the return, the value becomes None.

challenge icon

Challenge

Easy

In EventForm, refuse a date before today with the message The date cannot be in the past. An event today is fine.

Press Run and add an event dated yesterday.

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)
    description = forms.CharField(widget=forms.Textarea, required=False)
    capacity = forms.IntegerField(min_value=1)

All lessons in Forms

Practice on your own: Django playground