Bound and Unbound Forms
Part of the Forms section of Coddy's Django journey. Lesson 7 of 20.
Send the form with the date next friday: the page comes back empty, with only "Please check the form." The view drew a new, empty form, and the form it checked had the details.
A form built with data is bound: ContactForm(request.POST) holds what the visitor typed and, after is_valid(), the errors. ContactForm() is unbound: empty, with no errors. Drawn with {{ form }}, a bound form shows each value and, under a wrong field, its error, like Enter a valid date.
So a view with a form has three cases:
- A GET: render an unbound form.
- A POST that fails: render the bound form it checked.
- A POST that passes: save and redirect.
One render() at the end serves the first two.
Challenge
Easy- In
new_event, render the form that was checked after a failed POST, and an empty one on a GET. - Remove the
errormessage from the view and fromnew_event.html: the form shows its own errors now.
Press Run, send the form with the date next friday, and look under the date.
Try it yourself
from django.shortcuts import get_object_or_404, redirect, render
from .forms import EventForm
from .models import Event
def event_list(request):
q = request.GET.get("q", "")
events = Event.objects.all()
if q:
events = events.filter(title__icontains=q)
return render(request, "events/event_list.html", {"events": events, "q": q})
def event_detail(request, pk):
event = get_object_or_404(Event, pk=pk)
return render(request, "events/event_detail.html", {"event": event})
def new_event(request):
error = None
if request.method == "POST":
form = EventForm(request.POST)
if form.is_valid():
event = Event.objects.create(
title=form.cleaned_data["title"],
date=form.cleaned_data["date"],
place=form.cleaned_data["place"],
)
return redirect("events:detail", pk=event.pk)
error = "Please check the form."
return render(request, "events/new_event.html", {"error": error, "form": EventForm()})
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Forms
2Django Forms
A Django FormDrawing a FormPractice on your own: Django playground