这看起来一定非常简单,但我一直无法找到解决这个特定问题的答案。
本质上,我希望我的 Django 模板能够循环浏览我在该页面 View 中创建的列表。但是,当我尝试运行它时,我收到“属性错误:
‘list’对象没有属性‘get’”。我一直在尝试对 Django poll-app 进行一些扩展,这个应用程序的想法是让书籍按作者排序,进行投票。所以这个 View 将显示一个表格,其中一侧有作者姓名,以及作者每本书的投票总数。
这是模型。
class Author(models.Model):
author_name = models.CharField(max_length=200)
def __unicode__(self):
return self.author_name
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.title
这是我尝试按作者对投票进行分组并将其添加到列表中的 View 。
def totals(request):
a = Author.objects.order_by('author_name')
b = Book.objects.order_by('author__author_name')
total = []
for i in range(len(b)):
if i < len(b)-1:
x = b[i].votes
if b[i].author == b[i+1].author:
x += b[i+1].votes
else:
total.append(x)
else:
x = b[i].votes
total.append(x)
return total
return render(request, "book/totals.html", {"a":a, "total":total})
这是模板。 “a”上的第一个 for 循环工作正常,第二个 for 循环应该循环遍历不工作的“总计”。
<h1>Total Votes</h1>
<table style="border-collapse:collapse;">
<thead>
<tr>
<th colspan="2"><strong>Totals</strong></th>
</tr>
<tr style="border-bottom:1px solid black;">
<th style="padding:5px;"><em>Authors</em></th>
<th style="padding:5px;border-left:1px solid black;"><em>Votes</em></th>
</tr>
</thead>
{% for author in a %}
<tr>
<td>{{ author }}</td>
</tr>
{% endfor %}
{% for x in total %}
<tr>
<td>{{ total[x] }}</td>
</tr>
{% endfor %}
</thead>
好吧,我认为差不多就可以了。感谢所有读到这里的人。显然我对此还很陌生,所以如果有人有任何其他评论或反馈,我肯定会很高兴听到他们。 谢谢!
编辑:这是回溯 -
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/book/totals/
Django Version: 1.8.3
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
223. response = middleware_method(request, response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response
31. if response.get('X-Frame-Options', None) is not None:
Exception Type: AttributeError at /book/totals/
Exception Value: 'list' object has no attribute 'get'
最佳答案
您的 View 应返回 HTTP 响应。但是,您的 View 返回 total
,它是一个 list
。
return total
您应该删除此行,或更改它以使其返回 HTTP 响应。
关于django - django 模板中的 for 循环 - 列表对象没有属性 'get',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018885/