1# in books/models.py2from django.db import models
3classBook(models.Model):4 title = models.CharField(max_length=80)56# in books/views.py7from django.views import generic
8from django.http.response import HttpResponseBadRequest
9from django.shortcuts import get_object_or_404
10from.models import Book
11classBookList(generic.ListView):12 model = Book
13defget_context_data(self,**kwargs):14 ctx =super().get_context_data(**kwargs)15 pk = self.request.GET.get('pk',None)16if pk:17 ctx['current_book']= get_object_or_404(Book, pk=int(id))18else:19 ctx['current_book']= ctx['object_list'].first()20return ctx
21defget(self, request,*args,**kwargs):22 pk = self.request.GET.get('pk',None)23if pk:24try:25 _ =int(pk)26except ValueError:27return HttpResponseBadRequest()28returnsuper().get(request,*args,**kwargs)2930# in books/urls.py31from.views import BookList
32urlpatterns =[33 path('', BookList.as_view(), name='book-list'),34]3536# in <project>/urls.py37from django.urls import path, include
38urlpatterns =[39 path('books/',include("books.urls")),40]
html
1# in books/templates/books/book_list.html
2<html>3<body>4<div>{{ current_book.title }}</div>5<div>6<table>7 {% for book in object_list %}
8<tr><td>{{ book.title }}</td></tr>9 {% endfor }
10</table>11</div>12</body>13</html>