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

6👍

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

Leave a comment