django'Manager'对象不可迭代(但代码在manage.py shell中工作)

use*_*328 5 django templates exception

我是django的新手,并创建了一个与本教程中描述的民意调查网站没有太大区别的应用程序.在我得到的网站上:

Exception Type: TemplateSyntaxError
Exception Value:    
Caught TypeError while rendering: 'Manager' object is not iterable
Exception Location: /usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render, line 190
Run Code Online (Sandbox Code Playgroud)

指向标记错误lin line 4的模板(渲染时捕获TypeError:'Manager'对象不可迭代):

test
2   {% if clips %}
3       <ul>
4       {% for aclip in clips %}
5           <li><a href="/annotate/{{ aclip.id }}/">{{ aclip.name }}</a></li>
6       {% endfor %}
7       </ul>
8   {% else %}
9       <p>No clips are available.</p>
10  {% endif %}
Run Code Online (Sandbox Code Playgroud)

这是剪辑对象:

class Clip(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=30)
    url = models.CharField(max_length=200)
Run Code Online (Sandbox Code Playgroud)

和视图代码:

def index(request):
    #return HttpResponse("You're looking at clips.")
    mylist = []
    latest_clip_list = Clip.objects.all()#.values_list("name","id")#.order_by('-pub_date')[:5]
    print latest_clip_list
    return render_to_response('annotateVideos/index2.html', {'clips': latest_clip_list})
Run Code Online (Sandbox Code Playgroud)

当我从manage,py shell运行此代码时,没有异常:

In [2]: from annotateVideos import views

In [3]: f = views.index("")
[{'id': 6L, 'name': u'segment 6000'}]

In [4]: f.content
Out[4]: 'test\n\n    <ul>\n    \n        <li><a href="/annotate//"></a></li>\n    \n        </ul>\n'
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我发现很难调试,因为代码似乎在shell上工作但在Web服务器上没有.

谢谢,拉斐尔

Ian*_*and 17

您在视图代码中注释了很多部分,特别是在行中

latest_clip_list = Clip.objects.all()#.values_list("name","id")#.order_by('-pub_date')[:5]
Run Code Online (Sandbox Code Playgroud)

您收到的错误'Manager' object is not iterable将表明模板中的for循环正在尝试迭代管理器Clip.objects,而不是查询集Clip.objects.all().

仔细检查以确保您的视图实际读取

latest_clip_list = Clip.objects.all()
Run Code Online (Sandbox Code Playgroud)

并且只是看起来像

latest_clip_list = Clip.objects
Run Code Online (Sandbox Code Playgroud)