一、DetailView核心功能解析
1. 核心作用
from django.views.generic import DetailView
2. 核心属性配置
class ArticleDetailView(DetailView):
model = Article
template_name = 'detail.html'
context_object_name = 'post'
pk_url_kwarg = 'article_id'
slug_field = 'title'
slug_url_kwarg = 'article_title'
query_pk_and_slug = True
二、基础使用示例
1. 最小化实现
class BookDetailView(DetailView):
model = Book
template_name = 'books/detail.html'
2. URL配置
path('books/<int:pk>/', BookDetailView.as_view(), name='book-detail')
path('books/<slug:slug>/', BookDetailView.as_view(), name='book-detail-slug')
3. 模板示例
<!-- books/detail.html -->
<h1>{
{
object.title }}</h1>
<p>作者:{
{
object.author }}</p>
<div class="content">
{
{
object.content|safe }}
</div>
三、高级应用技巧
1. 自定义查询逻辑