Working with Forms & ModelForms
Django handles form rendering, validation, and serialization dynamically. You can create custom forms manually, or map forms directly to models using ModelForms.
1 Defining a ModelForm
Python — forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content", "category", "is_published"]
widgets = {
"title": forms.TextInput(attrs={"class": "form-control", "placeholder": "Enter title"}),
"content": forms.Textarea(attrs={"class": "form-control", "rows": 5}),
}
def clean_title(self):
title = self.cleaned_data.get("title")
if "spam" in title.lower():
raise forms.ValidationError("Spam titles are not allowed.")
return title
2 Handling Forms in Views
Python — views.py
from django.shortcuts import render, redirect
from .forms import PostForm
def create_post(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect("home")
else:
form = PostForm()
return render(request, "create_post.html", {"form": form})
3 Code Challenge
Challenge: Design a custom form with field validation validating that the password matches a secondary password verification field. Throw a validation error if they do not match.