Skip to content
Django

ModelForms

Build forms from models with validation and widgets.

By EZ4Code Team
formsvalidation

Code

from django import forms
from .models import Article

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ["title", "body", "is_published"]
        widgets = {
            "body": forms.Textarea(attrs={"rows": 10, "class": "editor"}),
            "is_published": forms.CheckboxInput(),
        }
        labels = {"title": "Headline"}

    def clean_title(self):
        title = self.cleaned_data["title"]
        if len(title) < 5:
            raise forms.ValidationError("Title too short.")
        return title

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("is_published") and not cleaned.get("body"):
            raise forms.ValidationError("Published articles need a body.")
        return cleaned

Explanation

ModelForm auto-generates form fields from a model's fields. The inner Meta class controls which fields are included and how they render via widgets. Custom clean_<field> and clean() methods add per-field and cross-field validation that runs on is_valid().

More Django Snippets