ModelForms — Auto-Generated Forms
ModelForm automatically creates a form from a Django model — fields, validation, and save() are all handled. It eliminates code duplication between models and forms, making CRUD operations trivial.
15 min•By Priygop Team•Updated 2026
ModelForm Basics
- Inherits from forms.ModelForm
- class Meta: model = Model, fields = [...]
- fields = '__all__' — Include all fields (dangerous!)
- exclude = ['field'] — Exclude specific fields
- form.save() — Creates or updates model instance
- form.save(commit=False) — Get object without saving
- Inherits model field validation automatically
ModelForm Example
ModelForm Example
# blog/forms.py
# from django import forms
# from .models import Post, Comment
# class PostForm(forms.ModelForm):
# class Meta:
# model = Post
# fields = ['title', 'content', 'category', 'tags']
# widgets = {
# 'title': forms.TextInput(attrs={
# 'class': 'form-control',
# 'placeholder': 'Post Title'
# }),
# 'content': forms.Textarea(attrs={
# 'class': 'form-control',
# 'rows': 10
# }),
# }
# class CommentForm(forms.ModelForm):
# class Meta:
# model = Comment
# fields = ['content']
# widgets = {
# 'content': forms.Textarea(attrs={
# 'rows': 3,
# 'placeholder': 'Write a comment...'
# }),
# }
# blog/views.py
# 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()
# form.save_m2m() # Save ManyToMany (tags)
# return redirect(post.get_absolute_url())
# else:
# form = PostForm()
# return render(request, 'blog/form.html', {'form': form})Tip
Tip
Override get_queryset() to filter data dynamically. Override get_context_data() to add extra variables to templates.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Overriding too many methods in CBVs. If you override more than 3-4 methods, a function-based view might be cleaner.
Practice Task
Note
(1) Override get_queryset to filter published posts. (2) Override get_context_data to add extra variables. (3) Test both.
Quick Quiz
Key Takeaways
- ModelForm automatically creates a form from a Django model — fields, validation, and save() are all handled.
- Inherits from forms.ModelForm
- class Meta: model = Model, fields = [...]
- fields = '__all__' — Include all fields (dangerous!)