ModelForm

Generate a form straight from a model with ModelForm.

Syntaxclass PostForm(forms.ModelForm): class Meta: model = Post

When a form maps directly to a model, use a ModelForm. It builds the fields from the model and can save the data with a single form.save() call.

Declare the model and fields in an inner Meta class.

Example

Example Β· python
# blog/forms.py
from django import forms
from .models import Post

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

# In a view:
# form = PostForm(request.POST)
# if form.is_valid():
#     form.save()   # creates the Post

When to use it

  • A developer uses ModelForm for a Post create page so the form fields are automatically derived from the model.
  • A team uses ModelForm.save() to insert a new database record directly from form data without writing SQL.
  • A developer uses the 'fields' Meta option to expose only a subset of model fields in the public-facing form.

More examples

Define a ModelForm

Creates a form that maps directly to the Post model, exposing only the specified fields.

Example Β· python
from django import forms
from .models import Post

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

Save a new record from form

Uses commit=False to set the author before saving, then calls save() to persist the record.

Example Β· python
def post_create(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect(post)
    else:
        form = PostForm()
    return render(request, "blog/post_form.html", {"form": form})

Edit an existing record

Passes instance=post to pre-populate the form with existing data for editing.

Example Β· python
def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk, author=request.user)
    form = PostForm(request.POST or None, instance=post)
    if form.is_valid():
        form.save()
        return redirect(post)
    return render(request, "blog/post_form.html", {"form": form})

Discussion

  • Be the first to comment on this lesson.
ModelForm β€” Django | SoundsCode