Django Template中使用含有类实例对象的字典时要注意的事项[初学者问题]
下面小弟来说下今天学Django模板时遇到的问题和解决的方法
在python idle里,我写入如下代码
- Python code
class Test: id = 0 name ='' passwd = '' def __init__(self, id, name, passwd): self.id = id self.name = name self.passwd = passwd
这是一个测试类的定义,很简单的一个类
然后我实例化了两次
- Python code
test1 = Test(0, 'kevin', '123')test2 = Test(1, 'cong', '234')
现在要测试的类和对象有了,我开始加入模板内容如下
- Python code
t = Template('this is a Test, test that {{id}}')c = Context({"id":test1.id,})print t.render(c)上面这个测试模板返回的内容如下
- Python code
this is a Test, test that 0
之后我想测试下如果直接传进去对象的成员变量,代码如下
- Python code
t = Template('this is a Test, test that {{id.id}}')c = Context({"id":test1,})print t.render(c)上面的这个测试模板也返回
- Python code
this is a Test, test that 0
上面的测试简单顺利,麻痹了我的神经,我就把类对象通过字典传到模板,现在开始要看到真正的问题了,测试的模板文件内容如下
- HTML code
<html><head><title></title></head><body><table > <tr> <td> {%for i in RecordInfo%} {{i.id}}<br>------------------------ {%endfor%} </td> </tr></table></body></html>不知道大家一眼看出来我犯的错误没有?
就是字典的成员函数in在调用时默认返回的是keys()的列表
这个
- Python code
{{i.id}}要用values返回的列表才是真正的类实例
修改关键代码如下
- Python code
{%for i in RecordInfo.values%} {{i.id}}<br>------------------------ {%endfor%}这样在源文件中传到模板里的类实例就可以被正常访问了
此错误比较低级,发此贴给大家提个醒
以后编码时要认真
[解决办法]
这个django或者template没有任何关系。Python里的for k in {...}本来就是key。