Reputation: 9865
I have this function which is making a request to an api with get
. the response is coming back and expected and I am printing out each name of the objects returned to the terminal. But when I use the same for loop to print data in the template only the name of the last object is being rendered on the template page.
I was thinking maybe I am not executing my for loop properly but if that was true then why is my data outputting correctly in terminal.
In my view
def graphs(request):
if request.user.is_authenticated():
data = []
r = requests.get('https://api.deckbrew.com/mtg/cards')
jsonList = r.json()
cardData = {}
for cards in jsonList:
cardData['name'] = cards['name'] # Only last object name
print(cards['name']) # Prints to termainl correct
data.append(cardData)
return render(request, 'graphs/graphs.html', {'data': data})
else:
return redirect('index')
This is in my template # I only get the last objects name
{% for card in data %}
<tr>
<td>{{ card.name }}</td>
</tr>
{% endfor %}
When I move the data.append inside the for loop it appends the same name to the list for each time there is a card in the response.
for cards in jsonList:
cardData['name'] = cards['name']
print(cards['name'])
data.append(cardData)
Upvotes: 1
Views: 1681
Reputation: 22553
It's because you declared
cardData = {}
outside your loop and the same instance is being written over and the same dictionary is being pushed onto the array. On the last iteration the entire list has the last name.
Move that declaration inside the loop. Or better still, just append each card onto the list. Your indentation is wrong too. You only ever put the last instance on the results list. Do this:
for cards in jsonList:
data.append(cards)
Upvotes: 2
Reputation: 473813
You need to initialize the dictionary and call append()
inside the loop:
for cards in jsonList:
cardData = {}
cardData['name'] = cards['name']
data.append(cardData)
Or, even shorter (and faster), with a list comprehension:
data = [{'name': cards['name']} for cards in jsonList]
Upvotes: 1