ModelForm (Django)

A ModelForm is a Django form generated automatically from a model. It builds form fields from the model's fields and adds a save() method that creates or updates a database row, eliminating duplicate field declarations.

Django

Most forms exist to create or edit a model row, and a ModelForm removes the boilerplate. You declare an inner Meta with model = Post and fields = ['title', 'body'], and Django derives the form fields, widgets, and validation from the model definition.

Its big convenience is save(): after form.is_valid(), calling form.save() writes the data to the database, creating a new row or updating the instance you passed in. Pass commit=False to get the unsaved object first if you need to set extra fields (like the current user) before saving.

ModelForm powers the Django admin and most edit pages. Use fields to whitelist exactly which model fields appear; avoid fields = '__all__' on user-facing forms so users cannot set fields you did not intend.

Syntax

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "body"]

Examples

Python

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "body"]

# in a view, after is_valid():
# post = form.save(commit=False)
# post.author = request.user
# post.save()

Learn it in a lesson

See also

Back to the Dictionary