A Search Form
Part of the Forms section of Coddy's Django journey. Lesson 1 of 20.
Visitors cannot search the events board yet. A form is a set of fields and a button that sends what was typed to a URL.
A form that only reads data uses method="get": the browser puts each field in the URL's query string, as name=value. A size filter on a shop's page:
<form method="get">
<select name="size">
<option value="S">Small</option>
<option value="L">Large</option>
</select>
<button type="submit">Show</button>
</form>Choosing Large opens /products/?size=L. The field's name is the key, so the view reads it like any query string: request.GET.get("size", ""), with a default for the plain page.
After a search the page reloads, and the box is empty again. To keep the words in it, pass them back to the template and write them in the input's value.
Challenge
EasyAdd a search to the home page:
- Above the list in
event_list.html, a form that sends its field in the URL: an input namedqand aSearchbutton. - In
event_list, show only the events whose title containsq, ignoring capitals. - The box keeps what was searched.
Press Run and search for jazz.
Try it yourself
from django.shortcuts import get_object_or_404, render
from .models import Event
def event_list(request):
events = Event.objects.all()
return render(request, "events/event_list.html", {"events": events})
def event_detail(request, pk):
event = get_object_or_404(Event, pk=pk)
return render(request, "events/event_detail.html", {"event": event})
All lessons in Forms
Practice on your own: Django playground