I am trying to return the values from a Dict in Django.
My views.py
prints the the correct data in the terminal when doing a GET-request to my page, however, in my template I only get the last line of the dictionary.
I have tried looping the dict in my template and all sorts of combinations but I can't seem to make it work. Am I missing something? For instance, in the template below I print the entire dict. But it still only prints the last row somehow.
views.py
fruits = [
'Apple', 'Banana', 'Orange']
for fruit in fruits:
price_change = historical_prices['price_change'][::-1]
low_price = 0
for day in price_change:
if day < -0.1:
low_price = 1
else:
break
if low_price >= 0:
ls_dict = {'fruit': fruit, 'low_price': low_price}
print(ls_dict)
return render(request, "prices/index.html", {
"ls_dict": ls_dict,
})
Template
<p>{{ ls_dict }}</p>
Template output
{'fruit': 'Orange', 'low_price': 1}
Correct print which views.py produces
{'fruit': 'Apple', 'low_price': 1}
{'fruit': 'Banana', 'low_price': 3}
{'fruit': 'Orange', 'low_price': 1}
CodePudding user response:
The print()
seems correct, but you are just overriding the variable over and over again, thus ls_dict
will only be the set with the last iteration of the for
loop.
You can test this by print(ls_dict)
outside of the for
-loop
Try the following:
ls_list = []
for fruit in fruits:
price_change = historical_prices['price_change'][::-1]
low_price = 0
for day in price_change:
if day < -0.1:
low_price = 1
else:
break
if low_price >= 0:
ls_dict = {'fruit': fruit, 'low_price': low_price}
ls_list.append(ls_dict)
return render(request, "prices/index.html", {
"ls_list": ls_list,
})