Django · Lesson 4 of 5
Forms and the Admin
Validate input with ModelForm and manage data with the built-in admin.
- Intermediate
- 16 min read
- 3 objectives
Before this lessonLesson 3: Views, URLs and Templates
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>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")# Write your solution here
