[Django]-.items not working on defaultdict in Django template

9👍

This is a known issue in Django: you cannot iterate over a defaultdict in a template. The docs suggest that the best way to handle this is to convert your defaultdict to a dict before passing it to the template:

context['data'] = dict(assertion_dict)

The reason it doesn’t work, by the way, is that when you call {{ data.items }} in your template, Django will first attempt to find data['items'], and then data.items. The defaultdict will return a default value for the former, so Django will not attempt the latter, and you end up trying to loop over the default value instead of the dict.

Leave a comment