gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:29:23 26 4
gpt4 key购买 nike

我是 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

指向标记错误 lin 第 4 行的模板(渲染时捕获类型错误:'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 %}

这是剪辑对象:
class Clip(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=30)
url = models.CharField(max_length=200)

和 View 代码:
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})

当我从 manage,py shell 运行此代码时,也不异常(exception):
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'

有任何想法吗?
我发现很难调试,因为代码似乎在 shell 上运行,但不在 web 服务器上运行。

谢谢,
拉斐尔

最佳答案

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

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

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

仔细检查以确保您的 View 实际读取
latest_clip_list = Clip.objects.all()

而且不只是看起来像
latest_clip_list = Clip.objects

关于django 'Manager' 对象不可迭代(但代码在 manage.py shell 中有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com