我正在使用 Django 1.8.2,但在弄清楚如何迭代这个复杂的字典时遇到了一些麻烦。我正在尝试将此信息传递到我的模板并显示信息。
context = {'name': 'John', 'inventory': '[{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server" "brand": "Dell"}]'}
有任何想法吗?非常感激。
我正在使用 Django 1.8.2,但在弄清楚如何迭代这个复杂的字典时遇到了一些麻烦。我正在尝试将此信息传递到我的模板并显示信息。
context = {'name': 'John', 'inventory': '[{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server" "brand": "Dell"}]'}
有任何想法吗?非常感激。
在您的模板中:
{{ name }}
{% for item in inventory %}
{{ item.hardware }}
{{ item.brand }}
{% endfor %}
并阅读此文档:https ://docs.djangoproject.com/en/1.8/topics/templates/
检查你的字典,让它像这样,
context = {'name': 'John', 'inventory': '[{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server", "brand": "Dell"}]'}
并在模板中
{{ name }}
{% for item in inventory %}
{{ item.hardware }}
{{ item.brand }}
{% endfor %}
模板
{{ name }}
{% for item in inventory %}
{{ item.hardware }}
{{ item.brand }}
{% endfor %}
看法
您不能迭代字符串(除了迭代每个字符)。相反,您必须传递一个 dict(如果您的数据源是 JSON)或一个模型数组(数据库)。
在您的示例中:
import simplejson
inventory_dict = simplejson.loads('{"inventory": [{"hardware": "Desktop", "brand": "HP"}, {"hardware": "Server", "brand": "Dell"}]}')
context = {'name': 'John', }
context.update(inventory_dict)