【问题标题】:Django 1.8.2 - display dictionary of dictionary in templateDjango 1.8.2 - 在模板中显示字典的字典
【发布时间】:2015-06-10 07:42:31
【问题描述】:

我正在使用 Django 1.8.2,但在弄清楚如何迭代这个复杂的字典时遇到了一些麻烦。我正在尝试将此信息传递到我的模板并显示信息。

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

有什么想法吗?非常感谢。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 您的 dict 中有错误,列表前的附加引号和逗号丢失。

标签: python django templates dictionary django-1.8


【解决方案1】:

在您的模板中:

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

并阅读此文档:https://docs.djangoproject.com/en/1.8/topics/templates/

【讨论】:

    【解决方案2】:

    检查你的字典,把它变成这样,

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

    在模板中

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

    【讨论】:

      【解决方案3】:

      模板

      {{ 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)
      

      【讨论】:

      • try: import simplejson as json except ImportError: import json
      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多