class 基于详细视图未返回模板

class based detail view is not returning the template

在我的 article_details.html 页面中,我写了 {{post.title}} 但我的页面没有显示具体标题。我的应用程序名称是 post,模型名称是 BlogPost。 这是我的 views.py:

from django.shortcuts import render
from .models import *
from .forms import *
from django.views.generic import ListView,CreateView
from django.views.generic.detail import DetailView
def home(request):
return render(request,'post/home.html')

class HomeView(ListView):
      model = BlogPost
      template_name = "post/home2.html"

class ArticleDetailView(DetailView):
           model = BlogPost
          template_name = "post/article_details.html"
class AddPostView(CreateView):
    model = BlogPost
    template_name = "post/add_post.html"
    fields = '__all__'

这是我的urls.py

from post import views
from django.urls import path
from .views import HomeView,ArticleDetailView,AddPostView
app_name = 'post'
urlpatterns = [
         path('',views.home,name="home"),
         path('home2/',HomeView.as_view(),name = "home2"),
         path('article/<int:pk>',ArticleDetailView.as_view(),name = "article-details"),
         path('add_post/',AddPostView.as_view(),name="add_post"),
    ]

这是我的列表页面:post/home2。html

<ul>
{%for post in object_list %}
    <li><a href="{%url 'post:article-details' post.pk %}">{{post.title}}</a>-{{post.author}}<br/>
     {{post.body}}</li>
{%endfor%}
 </ul>

这是我的详细信息 page:article_details。html:

<h1>{{post.title}}</h1>
<small>by:{{post.author}}</small><br/>
<hr>
<br/>
<p>{{post.body}}</p>



enter code here

除非您定义 context_object_name,否则视图将通过您的模型名称的上下文参数发送对象(全部小写)。所以你应该通过 {{ blogpost.author }} 获得价值。或者,您可以像这样更新您的视图:

class ArticleDetailView(DetailView):
      model = BlogPost
      template_name = "post/article_details.html"
      context_object_name = 'post'

详情请见documentation on context object naming