Validating Django Forms
Validation checks form values before the program uses them. A bad value gets an error, not a crash.
Write the two forms
NameForm holds one field. ContactForm holds three fields.
from django import forms
class NameForm(forms.Form):
name = forms.CharField(max_length=50)
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
age = forms.IntegerField()
email = forms.EmailField()Check a good form
Is_valid checks the typed name. A good form prints True, and the checked name prints next.
form = NameForm({"name": "Sana"})
print(form.is_valid())
print(form.cleaned_data["name"])Check an empty form
An empty form fails the check. Is_valid prints False, and the error names the missing field.
form = NameForm({})
print(form.is_valid())
print(form.errors["name"][0])Check a bad number
Thirty is not a whole number, so the age field fails. The error says so in plain words.
form = ContactForm({"name": "Sana", "age": "thirty", "email": "sana@example.com"})
print(form.is_valid())
print(form.errors["age"][0])Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django import forms
class NameForm(forms.Form):
name = forms.CharField(max_length=50)
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
age = forms.IntegerField()
email = forms.EmailField()
form = NameForm({"name": "Sana"})
print(form.is_valid())
print(form.cleaned_data["name"])
bad = NameForm({})
print(bad.is_valid())
print(bad.errors["name"][0])
Key points
- Use form.is_valid() to check the typed values.
- Is_valid returns True when every value checks out.
- Cleaned data holds the checked values, ready to use.
- Use form.cleaned_data to read the checked values.
- Use form.errors to read the messages for bad values.
In this example, the setup lines configure Django. NameForm holds one field named name. The first form carries the name Sana. Is_valid prints True, and cleaned data gives back the checked name. The second form carries no data. Is_valid prints False. The error print shows the message for the missing name.
Note
Always call is_valid before reading cleaned data.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What should the program do before reading cleaned_data?