为什么我在django html模板里面打印不出来对象的for循环。总是报错啊。但是单独打印对象.属性 是可以的。
<!--打印不出对象,并且总是报错,什么原因?-->
<ul>
{% for k, v in user %}
<li>{{forloop.counter}}、{{k.v}}</li>
{% endfor %}
</ul>
<!--可以打印出-->
{% if user %}
<li> {{ user.name }}</li>
{% else %}
<li> no user </li>
{% endif %}
———————————— 报错的信息是:
TypeError at /blog/index/
'Person' object is not iterable
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/index/
Django Version: 1.5.5
Exception Type: TypeError
Exception Value:
'Person' object is not iterable
因为那个东西不支持使用 for 遍历。参见 Python 入门教程: http://docs.python.org/3/tutorial/controlflow.html#for-statements
嘿嘿,确实如楼上所说,User在这里只是一个对象,而不是一个列表,所以没能用for .. in ..
进行遍历。
最后一句TypeError Exception Value:
'Person' object is not iterable
说得很明白了。
如果你才学习django的话,可以去看看django book,或是官方文档中的入门例子,然后照着做下。