← Django tutorial

Django

Forms

A ModelForm generates form fields (and validation) straight from a model, so you don't hand-write and re-validate every input separately.

Example: a form generated from a model, and the view that uses it

# blog/forms.py
from django import forms
from .models import Post

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

# blog/views.py
def new_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = PostForm()
    return render(request, 'blog/new_post.html', {'form': form})
A GET request shows an empty form; a valid POST creates a new Post
row and re-shows the (now empty) form.

The request.method == 'POST' check is doing real work here — it's exactly what the Backend track's requests-and-responses lesson and the Flask tutorial's forms lesson both cover: one single view handling both "show the empty form" (GET) and "process the submitted data" (POST), branching on the method. form.is_valid() re-validates on the server regardless of anything the browser already checked — the same server-side validation principle the HTML tutorial's Forms lesson introduced, here handled almost entirely by Django rather than code you'd write by hand.

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

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

# blog/views.py
def new_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = PostForm()
    return render(request, 'blog/new_post.html', {'form': form})
Output
A GET request shows an empty form; a valid POST creates a new Post row and re-shows the (now empty) form.