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 responds with 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.
- In
books/views.py, writebook_detail(request, pk): it shows the book with that id, or responds with 404. - In
books/urls.py, route/books/<id>/, numbers only, to it asbook_detail. - In
home.html, link each title to its page. Only the title is the link:<a ...>Dune</a> (1965).
Click Dune on the home page, then open /books/999/: Page not found (404).
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