我无法在我的模板中循环访问 BlogPost 对象。由于某种原因,什么都没有出现。我可能忘记了什么。在外壳中,我可以毫无问题地获取对象。所以有些不对劲,我不知道是什么。
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>
这是我的结构。在底座中.html:
{% if '/' in request.path %}
{% else %}
{% include "includes/sidebar.html" %}
{% endif %}
侧边栏.html:
<div class="col-md-4 right">
{% include 'includes/latest_posts.html' %}
</div>
在我的 urls.py 中:
url("^$", direct_to_template, {"template": "index.html"}, name="home"),
您的页面是从另一个称为direct_to_template
的视图加载的,该视图与latest_posts
视图无关,因此它永远不会找到其上下文数据。
因此,现在需要发生两件事之一,要么您只需将代码从 latest_posts
re: 上下文数据使用到另一个视图中并将其包含在该上下文中。或者您创建一个指向该页面的网址
from views import latest_posts
url("^latest_posts$", latest_posts, name="latest_posts"),
现在,这将使您获得从url /latest_posts
显示的帖子,但它可能看起来不是很漂亮,可以选择让latest_posts
视图仍然加载基本模板.html这将使它看起来更像您期望的,尽管浏览有关模板继承的文档可能会有所帮助