[英]Trouble accessing value on a python dictionary which values are also dictionaries whithin a django template
传递给模板的字典不会产生任何值。
我尝试了各种访问字典值的方法,甚至自定义过滤器也没有运气。
def home_view(request, location):
cards = Site.objects.get(sites=location.upper()
).site_cards.all().values('cards')
vlans = json.load(open('allvendors/static/json/vlan.json'))
vlans_location = vlans[location]
home = {
"site": location,
"cards": cards,
"vlans": vlans_location,
}
return render(request, 'allvendors/home.html', {"home": home})
from django import template
register = template.Library()
@register.filter(name='lookup')
def lookup(dictionary, key):
return dictionary[key]
<QuerySet [{'cards': 'A'}, {'cards': 'B'}, {'cards': 'C'}, {'cards': 'D'}]>
{
'A':{
'vlan':'101'
},
'B':{
'vlan':'102'
},
'C':{
'vlan':'103'
},
'D':{
'vlan':'104'
}
}
{% load allvendors_filters %}
{% for card in home.cards %}
<div class="card mb-4 box-shadow shadow">
<div class="card-header">
<h4 id="whatfor" class="my-0 font-weight-normal">{{ card|title }}</h4>
</div>
<div class="card-body">
<h1 class="card-title pricing-card-title">Vlan:
<small class="text-muted">
<a href="#" target="_blank">
{{ home.vlans|lookup:card.cards }}
</a>
</small>
</h1>
<a class="text-decoration-none" href="{{ card|lower }}/">
<button id="seedata" type="button" class="btn btn-lg btn-block btn-outline-primary">See
Database</button>
</a>
</div>
</div>
{% endfor %}
问题是{{card}}本身有效,循环为每个卡1到3创建了一个div,但是{{card.vlan}}不会输出任何内容。
我觉得即时通讯输入有误,但我不知道原因或方式。
欢迎任何指针。
尝试重新考虑一下,使用了一个自定义过滤器:{{home.vlans | lookup:card.cards}}为我提供了一个对应于card的值的字典,并且字典本身是用html编写的:
{'vlan': '101'} written in Card A
{'vlan': '102'} written in Card B
...and so on
但是,如果尝试访问VLAN,则失败,并显示{{home.vlans | lookup:card.cards.vlan}}->无法在'A'中查找键[vlan]
在下面的选定标记答案中。
谢谢
一个快速的答案,我认为您for card in home.cards
的for card in home.cards
会迭代dict键,如果您也想获取密钥,请尝试将for card in home.cards.values
或for card_key, card_dict in home.cards.items
使用。
数据:
home_dict = [{'A':'v1','B':'v2'},{'C':'v3','D':'v4'}]
Jinja迭代:
{% for dict in home_dict %}
{% for key, value in dict.items %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
注意:确保您具有字典项目列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.