Forms and the Admin
Validate input with ModelForm and manage data with the built-in admin.
What you will learn
- Build a ModelForm
- Handle POST safely with CSRF
- Register models in the admin
Two of Django's biggest time savers: forms (validate and clean user input, redisplay errors) and the admin (a ready-made interface for managing your data).
ModelForm
A ModelForm builds a form from a model, including validation rules.
# blog/forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "body", "published"]
def clean_title(self):
title = self.cleaned_data["title"].strip()
if len(title) < 5:
raise forms.ValidationError("Title is too short.")
return titleHandling GET and POST
The same view shows the empty form on GET and processes it on POST. After a successful POST, redirect so refreshing does not resubmit.
from django.shortcuts import redirect, render
from .forms import PostForm
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.author # fill fields not on the form
post.save()
return redirect("blog:detail", pk=post.pk)
else:
form = PostForm()
return render(request, "blog/post_form.html", {"form": form})<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>{% csrf_token %} is required in every POST form. It defends against cross-site request forgery; without it Django rejects the submission with a 403.
The admin
Create a superuser, register your models, and Django generates a full create, edit, search and delete interface.
python manage.py createsuperuser
python manage.py runserver # then visit /admin/# blog/admin.py
from django.contrib import admin
from .models import Author, Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ("title", "author", "published", "created")
list_filter = ("published", "author")
search_fields = ("title", "body")
list_editable = ("published",)
admin.site.register(Author)Authentication
Django ships user accounts, sessions and password hashing. Protect a view with the login_required decorator.
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, "dashboard.html")Try it yourself
Add a ContactForm (a plain forms.Form, not tied to a model) with email and message fields, and make the view print the cleaned data on a valid submission.
Show solution
class ContactForm(forms.Form):
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea, min_length=10)
def contact(request):
form = ContactForm(request.POST or None)
if request.method == "POST" and form.is_valid():
print(form.cleaned_data)
return redirect("blog:list")
return render(request, "contact.html", {"form": form})