43T*_*cts 3 python django dictionary django-templates
我无法让.items在我的Django模板中工作:
从我的CBV的get_context_data复制并粘贴:
context['data'] = assertion_dict
context['dataitems'] = assertion_dict.items()
return context
Run Code Online (Sandbox Code Playgroud)
从我的模板中复制并粘贴:
<h3>data dump</h3>
{{data}}
<h3>dataitems</h3>
{% for key, value in dataitems %}
{{ key }}: {{ value }} <br/>
{% endfor %}
<h3>data.items</h3>
{% for key, value in data.items %}
{{ key }}: {{ value }} <br/>
{% endfor %}
<h3>Not found test</h3>
{{ i_dont_exist }}
Run Code Online (Sandbox Code Playgroud)
输出:
**data dump**
defaultdict(<class 'list'>, {<BadgeType: Talent>: [<BadgeAssertion: Blender Blue Belt>], <BadgeType: Achievement>: [<BadgeAssertion: MyBadge#1>, <BadgeAssertion: MyBadge#1>, <BadgeAssertion: MyBadge#2>], <BadgeType: Award>: [<BadgeAssertion: Copy of Copy of Blenbade>]})
**dataitems**
Talent: [<BadgeAssertion: Blender Blue Belt>]
Achievement: [<BadgeAssertion: MyBadge#1>, <BadgeAssertion: MyBadge#1>, <BadgeAssertion: MyBadge#2>]
Award: [<BadgeAssertion: Copy of Copy of Blenbade>]
**data.items**
**Not found test**
DEBUG WARNING: undefined template variable [i_dont_exist] not found
Run Code Online (Sandbox Code Playgroud)
为什么第二个版本没有工作,我在模板中使用data.items?
这是Django中的一个已知问题:您无法defaultdict在模板中迭代a.文档建议处理此问题的最佳方法是在将defaultdict其dict传递给模板之前将其转换为a :
context['data'] = dict(assertion_dict)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,它不起作用的原因是,当你{{ data.items }}在模板中调用时,Django将首先尝试查找data['items'],然后data.items.在defaultdict将返回默认值对于前者,所以Django会不会尝试后,你最终在默认值,而不是字典试图循环.