【发布时间】:2016-09-13 15:04:06
【问题描述】:
我试图仅在 Django 模板中进行第一次或第 n 次迭代。 通常我可以遍历使用,
{% for item in pModel %}
{{ item.post }}
{% endfor %}
我需要第一次迭代,但也想知道如何获得第 n 次迭代,
{{ pModel.0.post }}` 什么都不显示,也没有错误。
我不想遍历 pModel 中的每个对象。
我已经尝试了所有组合,即
{{ pModel[0][post] }}
{{ pModel.0.[post] }}
{{ pModel[0].post }}
{{ pModel[0][post] }}
{{ pModel.[0][post] }}
{{ pModel.[0].[post] }} etc.
pModel 来自这个视图,
def profile(request, id):
pk = id
name = User.objects.all().filter(id=pk)
pModel = reversed(PostModel.objects.all().filter(author = name[0]))
# user_instance = User.objects.all().filter(username = request.user)
return render(request, 'profile.html', {'pModel': pModel, 'current_time': timezone.now()})
下面什么都不显示,
<strong>{{ pModel.first.post }}</strong>
在同一个模板中,我使用了正确显示的 pModel,因此我知道 pModel 正在工作。完整的模板,
{% extends 'index.html' %} {% block homepage %}
<div class="post">
{% if pModel %}
<h3>Profile for <strong>{{ pModel.first.post }}</strong></h3>
<p>Last logged in: {{user.last_login|timesince:current_time}} ago on {{ user.last_login }}</p>
<p>Joined {{user.date_joined|timesince:current_time}} ago on {{ user.date_joined }}</p>
{% endif %}
{% if pModel %}
<div class="table-responsive">
<table class='table table-striped table-hover'>
<thead>
<tr>
<th>{{user.username}}'s posts</th>
<th>Topic</th>
<th>Topic Started By</th>
<th>Last Active</th>
<th class="table-cell-center">Views</th>
</tr>
</thead>
<tbody>
{% for item in pModel %}
<tr>
<td><a href="{% url 'thread' item.topic_id %}">{{ item.post }} uuu {{ pModel.0}}</a></td>
<td>{{ item.topic.topic }}</td>
<!-- item.topicid.authorid_id -->
<td><a href="{% url 'profile' user.id %}">{{ item.topic.topicAuthor }}</a></td>
<td class="icon-nowrap">{{ item.pub_date|timesince:current_time}}</td>
<td class="table-cell-center">{{ item.topic.views }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
{% endblock %}
【问题讨论】:
-
什么是
pModel?.0.应该适用于数组.. -
pModel 在视图中创建,并已添加到原始问题中。
-
是的,但它有
post字段吗?pModel是否返回结果?pModel.0显示什么?请尝试创建一个 minimal reproducible example 来演示问题。