neo
neo

Reputation: 34

Nested for loop in Django Template not able to loop through a dictionary item

Part of a small ecommerce project I'm trying to build.

The views.py function that displays the order_info

@login_required
def past_orders_view(request):
    print (request.user)
    allOrders = Order.objects.filter(full_name=request.user)
    return render(request, "orders.html", {'Orders':allOrders})

The allOrders queryset from db looks like, which will display the orders for the particular logged in user:

<QuerySet[<Order: 13-{'Zenbook 14': '82990.00', 'iPhone 11 64gb': '61999.00'}-godric-+919871199215>]>

In template, I have something like this:

<table class="table table-striped">
 <head>
   <tr>
     <th> Ordered Date </th>
     <th> Status </th>
     <th> Product Name </th>
     <th> Price </th>
   </tr>
 </thead>
<tbody>
{% for order in Orders %}
   <tr>
    <td> {{order.date}} </td>
    <td> {{order.status}} </td>
    <td> {{ order.items_json }} </td>
    <td> {{ order.items_json }} </td>
   </tr>
{% endfor %}
</table>

Also, in view.py the model object for Order saves these info when placing an order

order = Order(items_json=items_json, full_name=name, town_or_city=city,                  
              phone_number=phone, status=status, date=timezone.now())
order.save()

So, the Order objects such as full_name, status, date can be directly accessed through a for loop in the template, and displayed as desired in the HTML. The problematic part is looping through the dictionary which has product name as key, and it's price as the value. Already tried nested for loops, couldn't get the answer.

Tried loop sample:

{% for order in Orders %}
   <tr>
    {% for key,value in order.items_json.items %}
       <tr>
        <td> {{order.date}} </td>
        <td> {{order.status}} </td>
        <td> {{ key}} </td>
        <td> {{ value }} </td>
      </tr>
   {% endfor %}
  </tr>
{% endfor %}

Help needed!!!

Upvotes: 0

Views: 269

Answers (1)

FalseDev
FalseDev

Reputation: 484

Or simply make this part of your view and pass it along the context

If you want reuse this in multiple locations you can create a simple custom template tag as provided here

Example for your case:

class tuple_to_object:
  def __init__(self, input_tuple):
    self.key = input_tuple[0]
    self.value = input_tuple[1]

def get_key_values(dictionary):
  l = list(dictionary.items())
  return [tuple_to_object(item) for item in l]

...
orders = get_key_values(User.order_set.all()
render(request, 'path/to/view.html', {"orders":orders)})

And in your views:

{% for order in orders %}
  {{order.key}}
  {{order.value}}
{% endfor %}

Note: This isn't tailor fit to your question but the method is the same

Upvotes: 1

Related Questions