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.
- In
event_list.html, above<ul class="events">, add a form withmethod="get"holding an input namedqand aSearchbutton. - In
event_list, keep the events whose title hasq, ignoring capitals. - Pass
qto the template for the input'svalue, so a search forMeetupstays in the box.
Search for jazz: only Friday Jazz Night is left, and the box still says 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