Django模板报错:无法解析item.get(column)中的'(column)'部分
Django模板动态取字典值报错:Could not parse the remainder: '(column)' from 'item.get(column)'
问题原因
Django模板语法不支持用变量作为键调用字典的get()方法,也不支持item[column]这种变量索引写法——模板只能识别固定键(比如item.Year或item['Year']),没法用动态变量column指定要取的键。
另外你代码里还有两处拼写错误,会导致数据取不到:
- 视图中
columns列表里的ProductGroupe多了个e,要和values()里的ProductGroup保持一致 annotate(Januaru=Sum('January'))里的字段名拼错成Januaru,需改成January才能和columns里的字段对应
解决办法
最推荐:自定义模板过滤器
在你的Django应用下新建templatetags目录(必须包含空的__init__.py文件),然后创建custom_filters.py文件:
from django import template register = template.Library() @register.filter def get_item(dictionary, key): # 键不存在时返回空字符串,避免页面报错 return dictionary.get(key, '')
接着在模板开头加载这个过滤器,用它动态取值:
{% load custom_filters %} <table> <thead> <tr> {% for column in columns %} <th>{{ column|title }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for column in columns %} <td>{{ item|get_item:column }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
备选:视图层转数据格式
如果不想写过滤器,可以在视图里把values()返回的字典转成可通过属性访问的对象,再配合内置过滤器使用:
# views.py顶部导入依赖 from types import SimpleNamespace # ... 原有代码处理完data之后 ... data = [SimpleNamespace(**item) for item in data] return render(request, "home.html", {'data': data, 'columns': columns})
模板里这样写:
<table> <thead> <tr> {% for column in columns %} <th>{{ column|title }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for column in columns %} <td>{{ item|attr:column }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
最后务必修正视图里的两处拼写错误,否则即使解决了模板问题,部分字段还是会显示为空。
内容的提问来源于stack exchange,提问作者ArsNova
相关产品推荐
相关产品推荐

