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 cleanedExplanation
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
Model Definition
Define a Django model with field types and meta options.
ORM QuerySet
Filter, exclude, annotate and chain QuerySets.
Class-Based Views
Use generic class-based views for common CRUD flows.
URL Routing
Wire URLs to views with path converters and includes.
Template Tags
Use built-in tags and filters in Django templates.
Admin Customization
Customize the Django admin with list_display and actions.