需求:- 自己使用ListView,DetailView
书籍列表
点击列表显示书的详情
源码解析ListView
继承自MultipleObjectTemplateResponseMixin TemplateResponseMixin
BaseListView
MultipleObjectMixin
ContextMixin
View
dispatch
App/urls.py
urlpatterns = [
url(r'^hello/', views.HelloListView.as_view()),
url(r"^books/(?P<pk>\d+)", views.BookDetailView.as_view(), name='book_detail'),
]
App/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from App.models import Book
class HelloListView(ListView):
template_name = 'hello_list.html'
queryset = Book.objects.all()
class BookDetailView(DetailView):
template_name = 'book_detail.html'
queryset = Book.objects.all()
templates/book_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
{% for book in object_list %}
<li><a href="{% url 'app:book_detail' pk=book.id %}">{{ book.b_name }}</a></li>
{% endfor %}
</ul>
</body>
</html>
templates/list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
{% for book in object_list %}
<li><a href="{% url 'app:book_detail' pk=book.id %}">{{ book.b_name }}</a></li>
{% endfor %}
</ul>
</body>
</html>