What is the difference between a Form and a ModelForm in Django?
Last updated
A Form is a standalone collection of fields you define manually, while a ModelForm auto-generates its fields from a model and can save validated data directly to the database. Use a ModelForm when the form maps to a model; a plain Form when it doesn't.
Form:You declare every field explicitly; not tied to any model.
Best for inputs without a database table behind them (search, contact, login, filters).
You handle saving/processing the
cleaned_datayourself.
ModelForm:Builds fields automatically from a model via an inner
Metawithmodelandfields.Provides
save()to create or update the model instance, and includes model-level validation.Reduces duplication: field types, max lengths, and constraints come from the model.
Shared behavior: Both validate via
is_valid()and supportclean()/clean_<field>()hooks;ModelFormsimply subclassesBaseFormwith model wiring.
[lang:python]
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'body']
form = ArticleForm(request.POST)
if form.is_valid():
form.save() # creates/updates the Article
- https://github.com/endormi/awesome-dj
- https://www.freecodecamp.org/news/build-and-deploy-a-fitness-tracker-using-python-django-and-pythonanywhere/
- https://developer.mozilla.org/ko/docs/Learn_web_development/Extensions/Server-side/Django/Forms
- https://developer.mozilla.org/zh-TW/docs/Learn_web_development/Extensions/Server-side/Django/Forms