1.ModelForm
ModelForm generates form fields automatically from a model's fields, declared via a Meta class naming the model and which fields to include. save() creates or updates a real model instance directly — save(commit=False) returns the unsaved instance for further changes first.
Key features
- Meta.model names the model; Meta.fields lists which model fields become form fields — "__all__" works but is a security risk (new model fields are exposed automatically)
- Field types are inferred from the model: CharField → CharField, ForeignKey → ModelChoiceField, and so on
- required=True unless the model field has blank=True; label defaults to the model field's verbose_name
- ArticleForm(instance=article) pre-fills the form for editing; ArticleForm(request.POST, instance=article) binds it for saving the same instance
- save(commit=False) returns the unsaved instance — needed to set a field (like created_by) before the real save(), or before save_m2m() for a ManyToManyField
ModelForm.Meta options
- Article (model)
- title, body, category
- ArticleForm
- Meta.model + Meta.fields
- is_valid()
- save()
- creates or updates the instance
Command
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ["title", "body"]
form = ArticleForm(request.POST, instance=article) # editing an existing Article
if form.is_valid():
form.save()ModelForm generates fields from Meta.model/fields and knows how to save() directly — use commit=False to set a field the form doesn't expose before the real save; always use an explicit fields list, never "__all__".