Python 理想页面未显示

Python 理想页面未显示,python,django,Python,Django,理想页面未显示。 我在views.py上写的 def top(request): content = POST.objects.order_by('-created_at')[:5] return render(request, 'top.html',{'content':content}) def detail(request,pk): content = POST.objects.order_by('-created_at')[:5] return rend

理想页面未显示。 我在views.py上写的

def top(request):
    content = POST.objects.order_by('-created_at')[:5]
    return render(request, 'top.html',{'content':content})

def detail(request,pk):
    content = POST.objects.order_by('-created_at')[:5]
    return render(request, 'detail.html',{'content':content})
在top.html中

<div>
         {% for item in content %}
            <h2>{{ item.title }}</h2>
            <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p>
         {% endfor %}
</div>

{content%%中的项目为%1}
{{item.title}

{%endfor%}
detail.html

<div>
   <h2>{{ content.title }}</h2>
   <p>{{ content.text }}</p>
</div>

{{content.title}
{{content.text}

在URL.py中

urlpatterns = [
    path('top/', views.top, name='top'),
    path('detail/<int:pk>/',views.detail , name='detail'),
]
urlpatterns=[
路径('top/',views.top,name='top'),
路径('detail/',views.detail,name='detail'),
]

当我访问top方法时,会显示top.html。当我单击SHOW DETAIL url link时,会显示DETAIL.html。但在这个DETAIL.html中,内容始终是相同的。我想在单击此链接时创建一个系统,每个content.pk都会更改detail的内容。但是现在我的系统不是我理想的系统。为什么我的系统总是返回detail.html中的相同内容?我应该如何解决这个问题?

好吧,你不是在拉所请求的对象-拉列表是同一个查询。您需要使用
Model.objects.get()
来检索对象的详细信息

def detail(request,pk):
    # Get the object with the matching pk
    content = POST.objects.get(id=pk)
    return render(request, 'detail.html',{'content':content})
您还应该考虑使用
DetailView
ListView
来简化您的工作

In

def detail(request,pk):
    content = POST.objects.order_by('-created_at')[:5]
    return render(request, 'detail.html',{'content':content})
您没有使用主键(
pk
)执行任何操作。你去数据库获取最近的5篇文章。你不希望它是:

def detail(request,pk):
    content = POST.objects.get(pk=pk)
    return render(request, 'detail.html',{'content':content})
?


由于您这样做是为了查看,我建议您也查看一下我认为您在
top.html
中使用了
content
变量而不是
item
,它总是从列表中获取第一个元素的
pk
。检查下面的代码

<div>
         {% for item in content %}
            <h2>{{ item.title }}</h2>
            <p><a href="{% url 'detail' item.pk %}">SHOW DETAIL</a></p>
         {% endfor %}
</div>

{content%%中的项目为%1}
{{item.title}

{%endfor%}
thx你的答案。我写了你的代码,但它不起作用。detail.html不显示任何内容。当我打印出print(content)in detail方法时,它只显示标题(我认为内容有标题和文本)。但我知道可以得到内容的值。但是当我写
{content}
in detail.html时,没有显示任何内容。我应该如何修复此问题?您是否尝试像以前那样执行
{{content.title}
?而且我刚刚意识到链接应该是

-
item.pk
而不是
content.pk
。当我写
{content.title}}
时,在html中显示了`。所以我认为用这种方式无法获得值。我认为content.pk是正确的,因为当我写item.pk时,NoReverseMatch错误发生。thx你的答案。我写了你的代码,但它不起作用。detail.html不显示任何内容。当我打印出print(content)in detail方法时,它只显示标题(我认为内容有标题和文本)。但我知道内容的值是可以得到的。但是当我在detail.html中写
{content}
,没有显示任何内容。我应该如何解决此问题?