📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Django Framework Django Forms

Django Forms

5 min read Quiz at the end
Build ModelForms with clean_() validators and custom widget attributes.

Django Forms

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model  = Post
        fields = ["title", "body", "tags", "is_draft"]
        widgets = {
            "body": forms.Textarea(attrs={"rows": 10, "class": "editor"}),
        }

    def clean_title(self):
        title = self.cleaned_data["title"]
        if len(title) < 5:
            raise forms.ValidationError("Title must be at least 5 characters.")
        return title

    def clean(self):
        cleaned = super().clean()
        if not cleaned.get("is_draft") and not cleaned.get("body"):
            raise forms.ValidationError("Published posts must have a body.")
        return cleaned

# Template
# {{ form.as_p }}
# {{ form.as_table }}
# {% csrf_token %}
# {{ form.title }}
# {{ form.title.errors }}