Django 1.8.2 - display dictionary of dictionary in template

180 views Asked by At

I am using Django 1.8.2 and I am having some trouble figuring out how to iterate over this complex dictionary. I am trying to pass this information onto my template and display the information.

context = {'name': 'John', 'inventory': '[{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server" "brand": "Dell"}]'}

Any ideas? Much appreciated.

3

There are 3 answers

0
Sylvain Biehler On

In your template :

{{ name }}
{% for item in inventory %}
  {{ item.hardware }}
  {{ item.brand }}
{% endfor %}

And read this documentation: https://docs.djangoproject.com/en/1.8/topics/templates/

1
laffuste On

Template

{{ name }}
{% for item in inventory %}
    {{ item.hardware }}
    {{ item.brand }}
{% endfor %}

View

You cannot iterate a string (besides iterating each character). Instead, you will have to either pass a dict (if your data source is JSON) or an array of model (database).

In your example:

import simplejson
inventory_dict = simplejson.loads('{"inventory": [{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server", "brand": "Dell"}]}')
context = {'name': 'John', }
context.update(inventory_dict)
0
AudioBubble On

Check your dictionary and make it like this,

context = {'name': 'John', 'inventory': '[{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server", "brand": "Dell"}]'}

and in template

{{ name }}
{% for item in inventory %}
  {{ item.hardware }}
  {{ item.brand }}
{% endfor %}