An Author Page
Part of the Models and the Admin section of Coddy's Django journey. Lesson 23 of 23.
The last piece: every author gets a page of their own, linked from everywhere an author's name appears. It is the book page you built in this section, for another model.
Think about the three ways in. A visitor on /authors/ clicks a name. A visitor on a book's page clicks "by Frank Herbert". And someone types the address of an author who does not exist, and should get a 404, not a crash.
Build every link with {% url %} and the author's id, so the links follow urls.py if it ever changes.
Challenge
MediumGive every author a page at /authors/<id>/ named author_detail:
- The author's name in an
<h1>, and links to their books. - An id with no author answers 404.
- On
/authors/, each name in its<h2>links to the page. - On a book's page, the author's name links to it.
Press Run and click a name on /authors/.
Try it yourself
from django.shortcuts import get_object_or_404, render
from .models import Author, Book
def home(request):
books = Book.objects.select_related("author")
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})
def search(request):
q = request.GET.get("q", "")
books = Book.objects.filter(title__icontains=q).select_related("author")
return render(request, "books/search.html", {"q": q, "books": books})
def author_list(request):
authors = Author.objects.prefetch_related("books")
return render(request, "books/author_list.html", {"authors": authors})
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