【发布时间】:2015-11-08 05:32:01
【问题描述】:
这看起来一定很简单,但我一直无法找到解决这个特定问题的答案。
本质上,我希望我的 Django 模板循环浏览我在该页面视图中创建的列表。但是,当我尝试运行它时,我得到“属性错误:
'list' 对象没有属性 'get'”。我一直在尝试对 Django poll-app 进行一些扩展,这个应用程序的想法是让书籍按作者排序,以便投票。所以这个视图将显示一个表格,其中一侧有作者姓名,以及作者每本书的总票数。
这是模型。
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
这是我尝试按作者分组投票并将它们添加到列表的视图。
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 循环工作正常,它的第二个应该循环遍历不起作用的“totals”。
<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>
好吧,我想差不多就可以了。感谢读到这里的任何人。显然我对此很陌生,所以如果有任何其他 cmets 或反馈任何人,我一定会很感激听到他们。 谢谢!
编辑:这是回溯 -
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'
【问题讨论】:
标签: django python-2.7 django-templates django-views