无法从我的模板(Django)中的BlogPost对象进行迭代

时间:2016-02-13 21:47:30

标签: python django mezzanine

我无法在模板中迭代BlogPost对象。由于某种原因,没有任何东西出现。我可能忘记了什么。在shell中我可以毫无问题地获得对象。所以出了点问题,我无法弄清楚是什么。

views.py:

def latest_posts(request):
    latest_posts = BlogPost.objects.all().filter(site_id=1)[:50]
    render(request, (settings.PROJECT_ROOT + "/main/templates/includes/latest_posts.html"), {"latest_posts": latest_posts})

latest_posts.html:

{% load pages_tags mezzanine_tags i18n accounts_tags %}

<div class="panel panel-default" >
    <div class="panel-heading">
      <h3 class="panel-title">{% trans "Latest Posts" %}</h3>
    </div>
    <div class="panel-body" style="padding:0;border:0px;">


      {% for lp in latest_posts %}
      <ul class="list-group-latest-posts">
        <li class="list-group-item-latest-posts">
          <img class="media-object left" src="#" width="40" height="40" alt="#">
          <p>{{ lp.title }}<br><span class="latest-post-name">user_name</span><span class="latest-post-divider"> - </span><span class="latest-post-time">6 Hours Ago</span></p>
        </li>
        </ul>
      {% endfor %}
      </div>
</div>

这是我的结构。在base.html中:

{% if '/' in request.path %}
{% else %}
  {% include "includes/sidebar.html" %}
{% endif %}

sidebar.html:

<div class="col-md-4 right">
      {% include 'includes/latest_posts.html' %}
</div>

在我的urls.py中:

url("^$", direct_to_template, {"template": "index.html"}, name="home"),

1 个答案:

答案 0 :(得分:1)

您的页面是从名为direct_to_template的其他视图加载的,该视图与latest_posts视图无关,因此它永远不会找到其上下文数据。

所以现在需要发生两件事中的一件,要么只是将latest_posts中的代码消耗掉:将上下文数据放入另一个视图中并将其包含在该上下文中。或者您创建一个指向该页面的网址

from views import latest_posts
url("^latest_posts$", latest_posts, name="latest_posts"),

现在,这将会显示来自网址/latest_posts的帖子,但它可能看起来不太漂亮,可能会让latest_posts视图仍然加载base.html虽然浏览template inheritance上的文档可能会有所帮助,但模板会让它看起来更像您期望的

相关问题