My defaultdict(list) won't show up on template but does in my view [duplicate]

老子叫甜甜 提交于 2019-12-01 09:22:47
Alasdair

This happens because of the way the Django template language does variable lookups. When you try to loop through the dictionaries items,

{% for key, value in confirmlist.items %}

Django first does a dictionary lookup for confirmlist['items']. As this is a defaultdict, an empty list is returned.

It's a cruel gotcha, that I've been stung by as well!

To work around this problem, convert your defaultdict into a dictionary before adding it to the template context.

context['confirmlist'] = dict(confirm_list)

Or, as explained by sebastien trottier in his his answer to a similar question, set default_factory to None before adding to the template context.

confirm_list.default_factory = None
context['confirmlist'] = confirm_list
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!