On Fri, Nov 7, 2008 at 2:51 AM, Hyungyong Kim <[EMAIL PROTECTED]> wrote:
> > Hi, > > Since a few hours ago, I've suffered following problem. > I found this problem is due to collections.defaultdict. > > Normal dictionary is working collectly, but defaultdict is not > working. > > >>> from django.template import Template, Context > >>> t = Template("{% for k,v in data.items %}{{ k }}: {{ v }}{% endfor %}") > >>> normal_dict = {'a':1, 'b':2} > >>> t.render(Context({'data':normal_dict})) > u'a: 1b: 2' > >>> > >>> from collections import defaultdict > >>> default_dict = defaultdict(int) > >>> default_dict[1]+=1 > >>> default_dict[2]+=1 > >>> default_dict[1]+=1 > >>> default_dict > defaultdict(<type 'int'>, {1: 2, 2: 1}) > >>> t.render(Context({'data':default_dict})) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/usr/lib/python2.5/site-packages/django/template/__init__.py", > line 176, in render > return self.nodelist.render(context) > File "/usr/lib/python2.5/site-packages/django/template/__init__.py", > line 768, in render > bits.append(self.render_node(node, context)) > File "/usr/lib/python2.5/site-packages/django/template/debug.py", > line 81, in render_node > raise wrapped > django.template.TemplateSyntaxError: Caught an exception while > rendering: 'int' object is not iterable > > Original Traceback (most recent call last): > File "/usr/lib/python2.5/site-packages/django/template/debug.py", > line 71, in render_node > result = node.render(context) > File "/usr/lib/python2.5/site-packages/django/template/ > defaulttags.py", line 122, in render > values = list(values) > TypeError: 'int' object is not iterable > > >>> > This is due to the interaction between the way in which Django attempts to resolve variables containing dots in templates (see http://docs.djangoproject.com/en/dev/topics/templates/#variables) and the fact that when you attempt to access a non-existent key in a defaultdict (that has a default_factory like you have specified) it automatically gets created. So, Django's first attempt to resolve data.items is a dictionary lookup of 'items' in your default dict (default_dict['items']), and instead of failing it returns the default value of 0. Since the dictionary acess attempt works, Django goes ahead and attempts to use the returned value instead of moving on an trying the other lookup methods. Karen --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---