当前位置:   article > 正文

Django DetailView视图

Django DetailView视图

Django的DetailView是一个用于显示单个对象详情的视图。下面是一个使用DetailView来显示单个书籍详情的例子。

1,添加视图

Test/app3/views.py

  1. from django.shortcuts import render
  2. # Create your views here.
  3. from django.views.generic import ListView
  4. from .models import Book
  5. class BookListView(ListView):
  6. model = Book
  7. context_object_name = 'books'
  8. template_name = 'books/book_list.html'
  9. paginate_by = 10 # 设置展示页数数据
  10. from django.views.generic import DetailView
  11. class BookDetailView(DetailView):
  12. model = Book
  13. context_object_name = 'book'
  14. template_name = 'books/book_detail.html'

2,添加路由地址

Test/app3/urls.py

  1. from django.urls import path
  2. from . import views
  3. from .views import BookListView
  4. from .views import BookDetailView
  5. urlpatterns = [
  6. path('books/', BookListView.as_view(), name='book_list'),
  7. path('books/<int:pk>/', BookDetailView.as_view(), name='book_detail'),
  8. ]

3,添加html代码

Test/templates/books/book_detail.html

  1. <!-- 在templates/books/book_detail.html中 -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>{{ book.title }}</title>
  6. </head>
  7. <body>
  8. <h1>{{ book.title }}</h1>
  9. <p>Author: {{ book.author }}</p>
  10. <p>Publication date: {{ book.publication_date }}</p>
  11. </body>
  12. </html>

3,访问页面

http://127.0.0.1:8000/app3/books/1/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/725120
推荐阅读
相关标签
  

闽ICP备14008679号