Menu
CoddyTech

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 icon

Challenge

Medium

Give every author a page at /authors/<id>/ named author_detail.

  1. In books/views.py, write author_detail(request, pk) to render books/author_detail.html: the name in an <h1>, a link to each book, and 404 for an unknown id. Add its route.
  2. In author_list.html, link each <h2> name to its author's page.
  3. In book_detail.html, link only the author's name: by <a href="/authors/1/">Frank Herbert</a>.

On /authors/, click Frank Herbert: his page links to Children of Dune and Dune.

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})
quiz iconTest yourself

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