【问题标题】:Why is my django template not outputting template variable object?为什么我的 django 模板没有输出模板变量对象?
【发布时间】:2015-02-18 18:10:39
【问题描述】:

我无法让我的模板输出我的 Postobjects,它代表博客文章。在我的主索引页面上,我的博客文章显示得很好,加载模板变量也没有问题。当用户单击其中一个存档日期(表示存档链接以显示某天某月的帖子)时,将使用相同的索引页面,但会使用不同的帖子集显示,按日期过滤。

views.py

def month(request, year, month):
    """Monthly archive."""
    posts = Post.objects.filter(created__year=year, created__month=month)

    d = dict(posts=posts, user=request.user, months=mkmonth_lst(), archive=True)
    return render(request, 'blog/index.html', d)

index.html

{% for post in posts.object_list %}
        <div class="blogpost">
            <div class="blogpost-title"><h2>{{ post.title }}<h2></div>
            <div class="blogpost-meta"><h4>{{ post.created }}</h></div>
            <div class="blogpost-body">{{ post.body|linebreaks }}</div>
            <div class="blogpost-comments"><a href="{% url 'post' post.id %}">Comments</a></div>
        </div>          
        {% endfor %}

在上述月份函数中,检索Post 对象列表并计算它们后,我可以看到它们正在被检索。问题是索引页没有输出它们。

有人可以帮忙吗?谢谢

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    在您的模板中,您应该遍历posts,而不是posts.object_list。

    【讨论】:

    • 谢谢!这很奇怪,我最初使用posts.object_list 来输出我的整个帖子集合,但是在输出帖子子集时它不起作用。
    • 您是在另一个视图中使用pagination,还是使用基于类的分页视图?
    • 是的,其他视图使用分页,但与months 共享模板。分页似乎仍然只使用posts,我是否有理由在某处阅读使用posts.object_list?
    • example in the docs 不循环通过object_list,所以我认为如果它适合你,循环通过posts 是可以的。
    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 2015-04-11
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多