我遇到了一个奇怪的问题......这段代码工作正常,直到我处理了其他一些观点,现在,它无法正常工作。
以下是我的观点:
def showTickets(request, project_slug):
project = Project.objects.get(slug=project_slug)
tickets = Ticket.objects.get(project=project)
payload = { 'project':project, 'tickets':tickets}
return render(request, 'project/tickets.html', payload)
模板:
{% extends 'project/base.html' %}
{% block title %}Tickets: {{project.name}}{% endblock %}
{% block main %}
<div id="project-nav">
<span><a href="/project/{{project.slug}}/">Tickets</a></span>
<span><a href="/book/{{book.slug}}{{book.name}}">Docs</a></span>
<span><a href="/project/{{project.slug}}/browse">Browser</a></span>
</div>
<div id="action-nav">
{% block actions %}
<span><a href="/project/{{project.slug}}/tickets/create">Create Ticket</a></span>
<span><a href="/project/{{ project.slug }}/tickets/recent/">Recent Activity</a></span>
<span><a href="/project/{{ project.slug }}/tickets/my/">My Tickets</a></span>
{% endblock %}
</div>
{% for ticket in tickets %}
<div class="ticket">
<div class="ticket-header">
<div class="ticket-title">
<a href="/project/ticket/{{ticket.pk}}">{{ticket.subject}}</a>
</div>
<div id="ticket-number">
#{{ticket.pk}}
</div>
<div id="ticket-state">
{{ticket.get_state_display}}
</div>
<div id="ticket-info">
Reported by {{ticket.created_by}} | created: {{ticket.created_on }} | modified: {{ticket.modified_on}}
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
错误:
Template error:
In template c:........\project\tickets.html, error at line 19
Caught TypeError while rendering: 'Ticket' object is not iterable
这工作正常,直到我处理其他一些观点...不确定为什么它现在不起作用?如果任何人可以帮助我,我会很感激!
答案 0 :(得分:7)
project = Project.objects.get(slug=project_slug)
tickets = Ticket.objects.get(project=project)
这两行是导致你烦恼的原因。它们不返回可迭代的(如列表),而是返回一个根本不可迭代的对象。而不是get,而是使用过滤器,它将返回一个列表。
答案 1 :(得分:3)
get()
方法返回单个对象。也许您打算使用filter()
方法?