Using ModelForm for Models
A snippet showing how to build forms from models with ModelForm.
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
isbn = models.CharField(max_length=13, unique=True)
def __str__(self):
return self.title
# forms.py
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ["title", "author", "published_date", "isbn"]
widgets = {
"published_date": forms.DateInput(attrs={"type": "date"}),
}
# views.py
from django.shortcuts import render, redirect
from .forms import BookForm
def add_book(request):
if request.method == "POST":
form = BookForm(request.POST)
if form.is_valid():
form.save()
return redirect("book-list")
else:
form = BookForm()
return render(request, "add_book.html", {"form": form})
# templates/add_book.html
<div class="row justify-content-center">
<div class="col-md-8 col-lg-6">
<form method="post" class="bg-white border rounded p-3">
{% csrf_token %}
<h5 class="mb-3">Add Book</h5>
{{ form.as_p }}
<button type="submit" class="btn btn-primary w-100">Save</button>
</form>
</div>
</div>
Explanation:
-
ModelFormauto-generates form fields from model fields, reducing boilerplate code. -
Use the
Metaclass to specify model and field list. -
Add
widgetsto customize rendering, like HTML5 date inputs.
- Category Forms & Validation
- Total Views 1085
- Last Modified 23 September, 2025
- Tags #forms #modelform #models #validation
Previous snippet
Basic Django Form Example
Next snippet