Reputation:
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 file
<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>
The error I am getting is -- Could not parse the remainder: '[item]['first_name']' from 'cand_list[item]['first_name']'
Upvotes: 0
Views: 2069
Reputation: 599450
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.
Secondly, in Django template language you always use dot notation, even for dictionary keys.
So, in your view:
for person in cand:
for item in paid['items']:
if item['email']== person.email and item['status']=='authorized':
....
and in your template:
{% for item in cand_list %}
<tr>
<td>{{ item.first_name }} {{ item.last_name }}</td>
<td>{{ item.email }}</td>
<td>{{ item.paid }}</td>
</tr>
{% endfor %}
Upvotes: 1
Reputation: 21
You don't need cand_len list, simply loop over cand_list (list of dict) and access with dict key.
<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 item in cand_list %}
<tr>
<td>{{ item.first_name }} {{ item.last_name }}</td>
..
..
</tr>
{% endfor %}
</table>
</div>
Upvotes: 0
Reputation: 1135
You can use {{ mydict.key }}
{% for candidate in cand_list %}
<tr>
<td>{{ candidate.first_name }} {{ candidate.last_name }}</td>
<td>{{ candidate.email }}</td>
<td>{{ candidate.paid }}</td>
</tr>
{% endfor %}
Upvotes: 0