Django·Django from project to API

Forms and validation

Build forms from models, validate input and render accessible errors.

Intermediate 14 min read Lesson 6 of 300 Challenge included
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.

forms.pyPython
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 minutes
Your turn

Add a slug field

Easy

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Authentication
Lesson 6 of 300 · 0% of course