Searching Books
Part of the Models and the Admin section of Coddy's Django journey. Lesson 15 of 23.
Your shelf needs a search box. A search page reads what the visitor typed from the address. In /search/?q=dune, the part after ? is the query string, and Django puts its pairs in request.GET, which works like a dictionary. The header's search box is a form that builds this address for you; the Forms section covers forms. A page for one genre could read it like this:
def by_genre(request):
genre = request.GET.get("genre", "fiction")
books = Book.objects.filter(genre=genre)
return render(request, "books/genre.html", {"genre": genre, "books": books}).get("genre", "fiction") returns the default when the address has no genre; request.GET["genre"] would raise there, a 500. Values are always text: ?page=2 gives "2". Every text contains the empty text, so __icontains="" matches every row.
Challenge
EasyAdd a search page. The template books/search.html is ready and expects q and books.
- A view
searchthat readsqfrom the address (empty text when missing) and finds the books whose title contains it, in any case. - The route
search/, namedsearch.
Press Run, search dune in the header, then open /search/.
Try it yourself
from django.shortcuts import get_object_or_404, render
from .models import Book
def home(request):
books = Book.objects.all()
return render(request, "books/home.html", {"books": books})
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, "books/book_detail.html", {"book": book})
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Models and the Admin
Practice on your own: Django playground