I'm trying to loop trough a dictionnary to create a simple table with the keys in a column and the values in the other.
So in my view I create the dictionnary vegetables_dict. I loop trhough the "items" of a "cartitem". If the item doesn't alrady exists I created a key with the name of a ForignKey of "item" and a value with its attribute quantity. Otherwise I increment the already existing key with the corresponding quantity
def dashboard_view(request):
carts = Cart.objects.filter(cart_user__isnull = False)
cartitems = CartItem.objects.all()
vegetables_dict = {}
for item in cartitems:
if item.stock_item.product_stockitem.name in vegetables_dict:
vegetables_dict[item.stock_item.product_stockitem.name] = item.quantity
else :
vegetables_dict[item.stock_item.product_stockitem.name] = item.quantity
context = {
'carts' : carts,
'cartitems' : cartitems,
'items' : vegetables_dict
}
return render(request, "maraicher/dashboard.html", context)
In the template i Tried :
<table>
<thead>
<tr>
<th colspan="2"> Récapitulatif de récole</th>
</tr>
</thead>
<tbody>
<th>Produit</th>
<th>Quantité</th>
<div>{{items}}</div>
{% for key, value in items.item %}
<tr>
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{{items}} render the dictionnary but the table is empty.
Any idea what is happening?
I aslo tried
{% for item in items %}
<tr>
<td>{{item}}</td>
<td>{{item.item}}</td>
</tr>
{% endfor %}
CodePudding user response:
This is how it should be in Django's template:
{% for key, value in items.items %}
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
CodePudding user response:
As mentionned by @user2390182 a "s" was missing, the correct syntaxe is
{% for key, value in items.items %}
CodePudding user response:
You must try this
{{items}}
{% for item in items %}
<tr>
<td>{{item}}</td>
</tr>
{% endfor %}