【问题标题】:django 2: rendering both single post and suggested posts on a templatedjango 2:在模板上呈现单个帖子和建议的帖子
【发布时间】:2018-09-09 21:16:49
【问题描述】:

我正在使用 Django 2,我想在单个文章博客页面中显示该文章的正文以及底部的 3 篇推荐文章。

很遗憾,显示 3 篇文章部分不起作用。我没有收到任何错误,只是没有更具体地显示循环中的块的任何部分:

我的看法

def detail (request, post_slug):
    post = get_object_or_404 (Post, slug=post_slug)
    suggested = Post.objects.all()[:3]

    return render (request, 'detail.html', {'post':post}, {'suggested':suggested})

以及显示建议的 html

<section class="read-next">

{% for a in suggested.all %}
    <a href="/{{a.slug}}" class="prev-post "  style="background-image:url({{a.image}})" >
        <div class="info">
            <div class="tag">We recommend</div>
            <h3 class="post-title">{{a.title}}</h3>
        </div>
    </a>
{% endfor %}
</section> <!-- .read-next -->

本节或我添加循环的任何地方都没有呈现任何内容。 在此先感谢您的帮助!

【问题讨论】:

  • 尝试 {% for a inSuggested %} 而不是 {% for a inSuggested.all %}

标签: django django-templates django-2.0


【解决方案1】:

这里有几个问题。

  1. 渲染调用错误。 render的格式是这样的:

    返回渲染(请求,模板名称,上下文)

context 是一个单独的字典,可用于在 html 页面上放置变量值。

您正在发送两个单独的字典进行渲染。因此,现在对您而言,上下文只是一个带有一个键的字典:“post”。包含建议的字典设置为 content_type 而不是发送到上下文。

所以你的视图需要变成:

 def detail (request, post_slug):
     post = get_object_or_404 (Post, slug=post_slug)
     suggested = Post.objects.all()[:3]
     context = {
         "post": post,
         "suggested": suggested
     }

     return render (request, 'detail.html', context)
  1. 因为您对 Post 对象 (suggested = Post.objects.all()[:3]) 的查询集进行了切片,所以它现在是一个查询列表,而不是一个可用的查询集。所以你把它当作一个列表来对待。基本上这意味着你不要使用{% for a in suggested.all %},因为在切片后建议不再有一个名为all 的方法。

所以你的模板应该使用{% for a in suggested %} 而不是{% for a in suggested.all %}。之前它不能以这种正确方式工作的原因是因为问题 #1,建议甚至不在上下文中。

【讨论】:

    【解决方案2】:

    当您调用render 时,您应该返回一个上下文字典:

    return render(request, 'detail.html', {'post':post, 'suggested':suggested})
    

    render 快捷方式的第四个参数是content_type,因此您当前的代码相当于:

    return render(request, 'detail.html', context={'post':post}, content_type={'suggested':suggested})
    

    【讨论】:

      猜你喜欢
      • 2010-11-12
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多