Menu
CoddyTech

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 checked the form that held what you typed, then threw it away and drew a new, empty one.

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, next to 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 icon

Challenge

Easy

Keep what the visitor typed after an error.

  1. In new_event, render the form you checked after a failed POST, and an empty EventForm on a GET.
  2. Remove the error message from the view and from new_event.html: the form shows its own errors now.

Send next friday as the date: your title stays, and Enter a valid date. appears above the Date box.

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()})
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Forms

Practice on your own: Django playground