【问题标题】:Django view: How to display data from a dictionaryDjango 视图:如何显示字典中的数据
【发布时间】:2011-05-17 15:41:32
【问题描述】:

我有一本像 {'a':{'c':2, 'd':4 }, 'b': {'c':'value', 'd': 3}} 这样的字典

如何将其显示到视图中的表格中?

【问题讨论】:

  • 递归自定义模板标签。

标签: python django django-templates django-views


【解决方案1】:

问题已回答here

总而言之,您可以像访问 python 字典一样访问代码

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

您可以使用 dict.items() 方法获取字典元素:

<table>
<tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
</tr>

{% for key, values in data.items %}
<tr>
    <td>{{key}}</td>
    {% for v in values[0] %}
    <td>{{v}}</td>
    {% endfor %}
</tr>
{% endfor %}
</table>

【讨论】:

    【解决方案2】:

    取决于你想怎么做。在 Django 模板中,访问键的方式与访问方法的方式相同。也就是Python代码之类的

    print my_dict['a']['c']    # Outputs: 2
    

    变成

    {{ my_dict.a.c }}    {# Outputs: 2 #}
    

    在 Django 模板中。

    【讨论】:

    • 它看起来模板中的 my_dict.iteritems() 不起作用?如何迭代?
    • @Mike:迭代 dict 会产生键。
    • 天啊,太晚了。我的意思是{% for key, item in my_dict.items %}
    【解决方案3】:

    遇到了类似的问题,我就这样解决了

    Python

    views.py
    #I had a dictionary with the next structure
    my_dict = {'a':{'k1':'v1'}, 'b':{'k2': 'v2'}, 'c':{'k3':'v3'}}
    context = {'renderdict': my_dict}
    return render(request, 'whatever.html', context)
    

    HTML

    {% for key, value in renderdict.items %}
        <h1>{{ key }}</h1>
        
        {% for k, v in value.items %}
          <h1>{{ k }}</h1>
          <h1 > {{ v }}</h1>
        {% endfor %}
    
    {% endfor %}
    
    The outputs would be 
    {{ key }} = a 
    {{ k }} = k1 
    {{ v }} = v1  #and so forth through the loop.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多