A Page for Each Book
Part of the Models and the Admin section of Coddy's Django journey. Lesson 14 of 23.
Each book needs a page at its own address: /books/1/, /books/2/. A path converter, from Django Basics, captures that number and passes it to the view. A page of the books from one year:
path("years/<int:year>/", views.books_of_year, name="books_of_year"),
def books_of_year(request, year):
books = Book.objects.filter(year=year)
return render(request, "books/year.html", {"year": year, "books": books})A page for one row names it by its primary key, pk: its id. get() on a missing row raises, and an exception in a view is a crash, 500 Server Error. get_object_or_404() from django.shortcuts answers 404 Page not found instead. It takes the model, then the conditions: get_object_or_404(Book, title="Emma").
To link to a route that captures a value, put the value after the name: {% url 'books:books_of_year' book.year %}.
Challenge
MediumGive every book a page. The template books/book_detail.html is ready and expects book.
- A view
book_detail(request, pk). An id with no book answers 404. - A route for
/books/<id>/namedbook_detail, matching numbers only. - On the home page, each title links to its page.
Press Run, click a title, then open /books/999/.
Try it yourself
from django.shortcuts import render
from .models import Book
def home(request):
books = Book.objects.all()
return render(request, "books/home.html", {"books": books})
All lessons in Models and the Admin
Practice on your own: Django playground