Forms and validation
Build forms from models, validate input and render accessible errors.
What you will be able to do
- Use forms.Form for custom input and ModelForm for models.
- Always include {% csrf_token %}.
- Render field errors next to the field.
- Call form.is_valid() before saving.
In plain English
Django forms handle rendering, binding and validation. A ModelForm derives fields from a model. Validation lives in the form, so the same rules apply whether the request comes from a browser or an API.
from django import forms
from .models import Lesson
class LessonForm(forms.ModelForm):
class Meta:
model = Lesson
fields = ('title', 'minutes', 'published')
def clean_minutes(self) -> int:
minutes = self.cleaned_data['minutes']
if minutes < 1 or minutes > 240:
raise forms.ValidationError('Minutes must be between 1 and 240.')
return minutesYour turn
EasyAdd a slug field
Add a slug ModelForm field for Lesson.
PYTHON · starter
fields = ('title', 'minutes')Check your understanding before moving on.
Knowledge checkQuestion 1
Which template tag adds CSRF protection to a form?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.