Reputation: 109
I'm sending a nested custom dictionary through my views, that nested dictionary is 'history'
def update_participation(request,user_id,event_id):
ev=Event.objects.get(id=event_id)
data=Participated(user=user_id,event=event_id)
data.save()
participated=Participated.objects.filter(user=user_id)
i=0
#Declared the dictionary history
history={}
#Adding values to dictionary
for partcipate in participated:
name=Event.objects.get(id=partcipate.event)
name1=name.name
fest=Fest.objects.get(id=name.fest_id.id)
fest1=fest.name
clg=College.objects.get(id=fest.clg_id.id).name
history[i]={'event':name1,'fest':fest1,'college':clg}
i+=1
messages.success(request,f'You have registered for {ev.name}')
#sending the dictionary to template
return render(request,'webpage/my_events.html',history)
Example of dictionary will look
history={0={'event':'css battle','fest':'verve','college':'jss'},
1={'event':'code wars','fest':'verve','college':'jss'},
2={'event':'hangman','fest':'phase shift','college':'bms'}}
I'm trying to access the values css battle, verve, jss like
{%extends 'webpage/base.html'%}
{%block content%}
<h2 style="margin:5px 30px;"><u>My Event History</u></h2>
<div style="margin:50px 0px 0px 270px" class='table'>
<table border='5'>
<tr>
<th>Event</th>
<th>Fest</th>
<th>College</th>
</tr>
{%for key,value in history.items%}
<tr>
<td>{{value.event}}</td>
<td>{{value.fest}}</td>
<td>{{value.college}}</td>
</tr>
{%endfor%}
</table>
</div>
{%endblock content%}
How am I supposed to iterate through the dictionary?
Upvotes: 0
Views: 115
Reputation: 1564
Aside from some query optimization you can do, you should change your data structure. That makes it easier to access as well. See below:
method.py
def update_participation(request, user_id, event_id):
event = Event.objects.get(id=event_id)
data = Participated(user=user_id, event=event_id)
data.save()
participated = Participated.objects.filter(user=user_id)
history = []
for partcipate in participated:
name=Event.objects.get(id=partcipate.event)
name1=name.name
fest=Fest.objects.get(id=name.fest_id.id)
fest1=fest.name
clg=College.objects.get(id=fest.clg_id.id).name
history.append({'event':name1,'fest':fest1,'college':clg})
messages.success(request,f'You have registered for {ev.name}')
#sending the dictionary to template
return render(request, 'webpage/my_events.html', context={'history': history})
template.html:
{% for item in history %}
<tr>
<td>{{item.event}}</td>
<td>{{item.fest}}</td>
<td>{{item.college}}</td>
</tr>
{% endfor %}
Also, please give your variables proper names instead of name1 and fest1.
Upvotes: 2