首页 > 解决方案 > 为什么不能使用数字在 Django 中引用字典

问题描述

我正在尝试使用使用循环创建的字典来呈现页面,并且在尝试在模板(.html)中引用它时,它正在打印数字,尽管该键的值

视图.py

dicti={}
key = range(len(OPTIONS)) # a tuple
for i in key:        
    dicti[i] = polls_model.objects.filter(options=i).count()
dicti.update({'len_of_key' : key})
print(dicti)
return render(request,'polls/thanks.html', dicti)

这将打印 {0: 1, 1: 1, 2: 0, 3: 0, 'len_of_key': range(0, 4)}

谢谢.html

<div class="row">
    {% for i in len_of_key %}
        <div class="column">
            <div class="card">
                <h3>
                    {{ i }}
                </h3>
            </div>
        </div>            
    {% endfor %}
</div>

当它运行时,我的输出中最终有 1,2,3,4。

一点帮助将不胜感激

标签: pythondjangoloopstemplatesfor-loop

解决方案


试着做:

return render(request,'polls/thanks.html', {'dicti': dicti})

{% for key, value in dicti.items %}
    <div class="column">
        <div class="card">
            <h3>
                {{ value }}
            </h3>
        </div>
    </div>            
{% endfor %}

推荐阅读