5

I have a list of dictionary in python i.e.

listofobs = [{'timestamp': datetime.datetime(2012, 7, 6, 12, 39, 52), 'ip': u'1.4.128.0', 'user': u'lovestone'}, {'timestamp': datetime.datetime(2012, 7, 6, 12, 40, 32), 'ip': u'192.168.21.45', 'user': u'b'}]

I want to use all of the keys and value of listofobs variable in a Django-template. For example:

For the first iteration:

timestamp = 7 july 2012, 12:39 Am
ip = 1.4.128.0
user = lovestone

and for the second iteration :

 timestamp = 7 july 2012, 12:40 Am
 ip =  192.168.21.45
 user = b

and so on ..

3 Answers 3

9
for a in listofobs:
    print str( a['timestamp'] ), a['ip'], a['user']

Will iterate over the list of dict's, then to use them in the template just wrap it in the needed django syntax and which is quite similar to regular python.

Sign up to request clarification or add additional context in comments.

Comments

3

Django template syntax lets you loop over a list of dicts:

{% for obj in listofobjs %}
    timestamp = {{ obj.timestamp }}
    ip = {{ obj.ip }}
    user = {{ obj.user }}
{% endfor %}

All you need to is make sure listofobjs is in your context for rendering.

Comments

2

Look at the examples for the built in for template tag.

Looping over items (your outer loop):

{% for obj in listofobjs %}
    {# do something with obj (just print it for now) #}
    {{ obj }}
{% endfor %}

And then loop over the items in your dictionary object:

{% for key, value in obj.items %}
    {{ key }}: {{ value }}
{% endfor %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.