Django模板无法遍历字典生成表格问题求助
原因与解决办法
模板1的错误
{% for key, value in items.item %}写法错误:items本身就是你传入的字典,不存在item属性。在Django模板中,要遍历字典的键值对,必须调用字典的items方法,正确写法是{% for key, value in items.items %}。
另外原模板里的<th>Produit</th>和<th>Quantité</th>没有包裹在<tr>标签内,不符合HTML规范,会导致表格结构异常。
模板2的错误
直接{% for item in items %}时,遍历的是字典的键(即商品名称字符串),所以{{item}}能显示名称,但{{item.item}}完全无效——字符串没有item属性,自然取不到值。
正确模板写法
推荐用第一种键值对遍历的方式,无需额外代码,简洁规范:
<table> <thead> <tr> <th colspan="2"> Récapitulatif de récole</th> </tr> </thead> <tbody> <tr> <th>Produit</th> <th>Quantité</th> </tr> {% for key, value in items.items %} <tr> <td>{{ key }}</td> <td>{{ value }}</td> </tr> {% endfor %} </tbody> </table>
如果一定要通过遍历键来取值,需要自定义Django过滤器:
- 在app目录下创建
templatetags文件夹,新建custom_filters.py文件:
from django import template register = template.Library() @register.filter def get_item(dictionary, key): return dictionary.get(key)
- 在模板开头加载过滤器:
{% load custom_filters %} - 修改循环部分:
<tr> <th>Produit</th> <th>Quantité</th> </tr> {% for product_name in items %} <tr> <td>{{ product_name }}</td> <td>{{ items|get_item:product_name }}</td> </tr> {% endfor %}
内容的提问来源于stack exchange,提问作者VincentAb
相关产品推荐
相关产品推荐

