Yon Yon - 3 months ago 5x
Python Question

Django templates and variable attributes

I'm using Google App Engine and Django templates.

I have a table that I want to display the objects look something like:

Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]

The Django template is:

<tr align="center">
{% for item in result.items %}
{% endfor %}

{% for user in result.users %}
<tr align="center">
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
{% endfor %}

Now the Django documention states that when it sees a . in variables

It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...

Yon Yon

I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works.

You install a custom filter into django which gets the key of your dict as a parameter

To make it work in google app-engine you need to add a file to your main directory, I called mine *django_hack.py* which contains this little piece of code

from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def hash(h,key):
    if key in h:
        return h[key]
        return None


Now that we have this file, all we need to do is tell the app-engine to use it... we do that by adding this little line to your main file


and in your template view add this template instead of the usual code

{{ user|hash:item }}

And its should work perfectly =)