Ticket #16335: defaultdict_conversion.diff

File defaultdict_conversion.diff, 1.6 KB (added by Nick Meharry, 13 years ago)

Convert defaultdicts to dicts before template lookups.

  • django/template/base.py

     
    672672        detail and shouldn't be called by external code. Use Variable.resolve()
    673673        instead.
    674674        """
     675        from collections import defaultdict
    675676        current = context
    676677        try: # catch-all for silent variable failures
    677678            for bit in self.lookups:
    678679                try: # dictionary lookup
     680                    if isinstance(current, defaultdict):
     681                        current = dict(current)
    679682                    current = current[bit]
    680683                except (TypeError, AttributeError, KeyError):
    681684                    try: # attribute lookup
  • tests/regressiontests/templates/context.py

     
    11# coding: utf-8
    2 from django.template import Context
     2from django.template import Context, Variable
    33from django.utils.unittest import TestCase
    44
    55
     
    1414        self.assertEqual(c.pop(), {"a": 2})
    1515        self.assertEqual(c["a"], 1)
    1616        self.assertEqual(c.get("foo", 42), 42)
     17    def test_defaultdict_conversion(self):
     18        from collections import defaultdict
     19        dd = defaultdict(list)
     20        dd['a'].extend([1, 2, 3, 4])
     21        dd['b'].extend([5, 6, 7, 8])
     22        context = Context({'dd': dd})
     23        var = Variable('dd.items')
     24        self.assertEqual(dd.items(), var.resolve(context))
Back to Top