[Answered ]-Django getting data in my template from nested dictionary(session)

1๐Ÿ‘

โœ…

A loop is used here, at each iteration, the desired value is taken from the nested dictionary from value and checked for presence using:

{% if value.quantity or value.price %}

templates(cart_page.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
</head>

<body>

{% for key, value in itens.items %}
    {% if value.quantity or value.price %}
    {{ 'key ='}} {{ key }}<br>
    {{ 'quantity ='}} {{ value.quantity }}<br>
    {{ 'price ='}} {{ value.price }}<br>
    {% endif %}
{% endfor %}
</body>
</html>

urls.py

urlpatterns = [
 path('city/', city),
]

views.py

def city(request):
    itens = {'3': {'quantity': 1, 'price': 4.0, 'totalitem': '4.00'}, '1': {'quantity': 1, 'price': 30.0, 'totalitem': '30.00'}}
    return render(request, "cart/cart_page.html", {"itens": itens})

Output

key = 3
quantity = 1
price = 4.0
key = 1
quantity = 1
price = 30.0

alternatively, you can read the values from the nested dictionary without a loop, as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
</head>

<body>
{{'3 key'}} {{'quantity ='}} {{itens.3.quantity}}   {{'price ='}} {{itens.3.price}}<br>
{{'1 key'}} {{'quantity ='}} {{itens.1.quantity}}   {{'price ='}} {{itens.1.price}}<br>
</body>
</html>
๐Ÿ‘คinquirer

Leave a comment