Checking Input
Part of the Forms section of Coddy's Django journey. Lesson 4 of 20.
Send the form with an empty title and the board gets an event with no name. Anything can arrive in request.POST, so a view checks it before saving.
When the input is wrong, the view saves nothing and does not redirect: it renders the form page again with a message. A table booking form that takes 1 to 8 guests:
guests = request.POST["guests"]
if not guests.isdigit() or not 1 <= int(guests) <= 8:
problem = "Choose between 1 and 8 guests."
return render(request, "tables/book.html", {"problem": problem})
Booking.objects.create(guests=int(guests))The check comes before create(): once the row is saved, the message is too late. For text, .strip() removes the spaces at both ends, so a title of only spaces becomes empty. The template shows the message only when there is one:
{% if problem %}
<p class="warning">{{ problem }}</p>
{% endif %}Challenge
EasyRefuse an event without a title:
- When the title is empty or only spaces,
new_eventshows the form page again withPlease give the event a title.above the form, and saves nothing. - A form with a title still adds the event and redirects to it.
Press Run and send the form with a title of three spaces.
Try it yourself
from django.shortcuts import get_object_or_404, redirect, render
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):
if request.method == "POST":
event = Event.objects.create(
title=request.POST["title"],
date=request.POST["date"],
place=request.POST["place"],
)
return redirect("events:detail", pk=event.pk)
return render(request, "events/new_event.html")
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