23👍
✅
You need to prepare your data beforehand, in this case you should pass list of two-tuples to your template:
{% for product, rating in product_list %}
<h1>{{ product.name }}</h1><p>{{ rating }}</p>
{% endfor %}
👤cji
103👍
Create a template tag like this (in yourproject/templatetags):
@register.filter
def keyvalue(dict, key):
return dict[key]
Usage:
{{dictionary|keyvalue:key_variable}}
- [Django]-Django override save for model only in some cases?
- [Django]-Visual Editor for Django Templates?
- [Django]-How to make two django projects share the same database
15👍
There is a very dirty solution:
<div>We need d[{{ k }}]</div>
<div>So here it is:
{% for key, value in d.items %}
{% if k == key %}
{{ value }}
{% endif %}
{% endfor %}
</div>
- [Django]-Distributing Django projects with unique SECRET_KEYs
- [Django]-Django orm get latest for each group
- [Django]-Django request get parameters
15👍
Building on eviltnan’s answer, his filter will raise an exception if key
isn’t a key of dict
.
Filters should never raise exceptions, but should fail gracefully. This is a more robust/complete answer:
@register.filter
def keyvalue(dict, key):
try:
return dict[key]
except KeyError:
return ''
Basically, this would do the same as dict.get(key, '')
in Python code, and could also be written that way if you don’t want to include the try/except block, although it is more explicit.
- [Django]-Composite primary key in django
- [Django]-Django: Adding "NULLS LAST" to query
- [Django]-How can I restrict Django's GenericForeignKey to a list of models?
Source:stackexchange.com