我想打印出每个选项得到的票数。我有这段代码在一个模板:
{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
Votes只是一个字典,而choices是一个模型对象。
它用下面的消息引发一个异常:
"Could not parse the remainder"
我想打印出每个选项得到的票数。我有这段代码在一个模板:
{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
Votes只是一个字典,而choices是一个模型对象。
它用下面的消息引发一个异常:
"Could not parse the remainder"
当前回答
类似于@russian_spy的回答:
<ul>
{% for choice in choices.items %}
<li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>
这可能适用于分解更复杂的字典。
其他回答
django_template_filter 过滤器名称get_value_from_dict
{{ your_dict|get_value_from_dict:your_key }}
您需要找到(或定义)一个'get'模板标签,例如,在这里。
标签定义:
@register.filter
def hash(h, key):
return h[key]
它的用法如下:
{% for o in objects %}
<li>{{ dictionary|hash:o.id }}</li>
{% endfor %}
没有比这更简单更好的解决方案了。还要去看医生。
@register.filter
def dictitem(dictionary, key):
return dictionary.get(key)
但有一个问题(也在这里讨论),返回的项目是一个对象,我需要引用这个对象的字段。不支持{{(schema_dict|dictitem:schema_code).name}}这样的表达式,所以我找到的唯一解决方案是:
{% with schema=schema_dict|dictitem:schema_code %}
<p>Selected schema: {{ schema.name }}</p>
{% endwith %}
更新:
@register.filter
def member(obj, name):
return getattr(obj, name, None)
所以不需要with标签:
{{ schema_dict|dictitem:schema_code|member:'name' }}
choices = {'key1':'val1', 'key2':'val2'}
下面是模板:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
基本上,.items是一个Django关键字,它将字典拆分为(键,值)对列表,很像Python方法.items()。这使得Django模板中的字典可以迭代。
理想情况下,您可以在选择对象上创建一个方法,或者在模型之间创建一个关系。执行字典查找的模板标记也可以工作。