我的基于班级的详细信息视图未正确返回模板

问题描述

在我的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>

这是我的详细信息页面: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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...