gpt4 book ai didi

python - html 模板中的 Django for 循环不显示

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:01 25 4
gpt4 key购买 nike

所以我试图获取最新的帖子,但遇到了一个问题,它不会显示该帖子

View .py

def latest_post(request):
latest = Post.objects.all().order_by('-id')[:1]
context = {'latestPost': latest}
return render(request, 'latest_post.html', context)

注意:我也尝试过这个,latest = Post.objects.all()

数据库中有条目,我用shell测试

from blog.models import Post
>>> Post.objects.all()
<QuerySet [<Post: test>, <Post: okay so>, <Post: okay-okay>]>

latest_post.html

{% for newest in latestPost %}
<section class="hero is-primary is-medium">
<div class="hero-body header">
<div class="container">
<div class="font">
<h1 class="title is-1">
<span id="blog_title">{{ newest.title }}</span>
</h1>
<h2 class="subtitle is-3 subup">
<span id="blog-subtitle">{{ newest.content|truncatechars:20|safe }}</span>
</h2>
<h2 class="subtitle is-5 dateup">
<span id="blogdate">{{ newest.timestamp }}</span><br><br>
<a href="{{ newest.blog_url }}" class="button is-danger is-large is-inverted">Read More >></a>
</h2>
</div>
</div>
</div>
</section>
{% endfor %}

在我的 blog_index.html 中,我有以下内容

{% extends "blog_base.html" %}
{% block blog_main %}
{% load staticfiles %}

{% include 'latest_post.html' %}
<p> other html here </p>
{% endblock %}

仅当我不使用 {% include 'latest_post.html' %} 时才显示 Latest_post.html

{% for newest in latestPost %}
{% endfor %}

所以我确信没有任何拼写错误会阻止latest_post.html 在我的索引页中显示。

我的模型.py

class Post(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
content = models.TextField()
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

def __str__(self):
return self.title

def blog_url(self):
return reverse("blogposts:blogdetail", kwargs={"slug": self.slug})

附加说明:python3、django 1.11、sqlite。此外,控制台中不会显示任何错误。任何帮助,将不胜感激!谢谢!!

最佳答案

看起来您正在将上下文变量直接传递给 latest_post.html:

return render(request, 'latest_post.html', context)

但是blog_index.html中没有这样的上下文变量latestPost。您需要做的是将上下文添加到 blog_index.html。也将其添加到 index View 中:

latest = Post.objects.all().order_by('-id')[:1]
context = {'latestPost': latest}
return render(request, 'blog_index.html', context)

您也可以使用first选择查询集中的第一个元素。

关于python - html 模板中的 Django for 循环不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com