在Django模板中的列表内访问字典值 [英] Access Dictionary Value inside list in Django Template
本文介绍了在Django模板中的列表内访问字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在列表中有一本字典.我想在Django模板中访问字典值.我该怎么办?views.py
I have a dictionary inside a list. I want to access dictionary value inside django template. How can I get that? views.py
def payment_status(request):
l1=[]
cand = CandidateDetail.objects.all()
for person in cand:
for num in range(0,paid['count']):
if paid['items'][num]['email']==person.email and paid['items']
[num]['status']=='authorized':
cand_dict = {'first_name':person.first_name,
'last_name':person.last_name, 'email':person.email,
'paid':'Yes'}
l1.append(cand_dict)
return render(request, 'desk/payment_status.html',{'cand_list':l1})
html文件
<div class="col-md-10">
<h3>Candidate Payment Status</h3>
<table class="cand_list">
<tr>
<th>Name</th>
<th>Email</th>
<th>Payment Status</th>
</tr>
{% for candidate in cand_list %}
<tr>
<td>{{ candidate.first_name }} {{ candidate.last_name }}</td>
<td>{{ candidate.email }}</td>
<td>{{ candidate.paid }}</td>
</tr>
{% endfor %}
</table>
</div>
我遇到的错误是-无法解析剩余的:'cand_list [item] ['first_name']'中的'[item] ['first_name']'
推荐答案
一开始,在某些长度范围内进行迭代从来都不是正确的事-无论是在Python中还是在模板.
For a start, iterating over a range of the length of something is never the right thing to do - either in Python or in a template.
第二,在Django模板语言中,即使是字典键,也总是使用点表示法.
Secondly, in Django template language you always use dot notation, even for dictionary keys.
所以,在您看来:
for person in cand:
for item in paid['items']:
if item['email']== person.email and item['status']=='authorized':
....
并在您的模板中:
{% for item in cand_list %}
<tr>
<td>{{ item.first_name }} {{ item.last_name }}</td>
<td>{{ item.email }}</td>
<td>{{ item.paid }}</td>
</tr>
{% endfor %}
这篇关于在Django模板中的列表内访问字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文