Home > OS >  Print dict in Django Template
Print dict in Django Template

Time:03-17

I have a dict defined like that:

table_data = [{'aircraft': <Aircraft: P28A I-ASTV>, 'row_data': [{'colspan': 2, 'booking_obj': <Booking: I-ASTV 2022-03-11 08:00:00 09:00:00>}, {'colspan': 4, 'booking_obj': <Booking: I-ASTV 2022-03-11 09:00:00 11:00:00>},...}]}]

I am printing in my template with some like that:

{% for row in table_data %} 
<tr>
   <th >{{row.aircraft.registration}}</th> #This is working correctly
{% for c, b in row.row_data %}
      <td colspan="">{{b}}</td> #This line just prints booking_obj
{% endfor %}
</tr>
{% endfor %}

but what I am trying to achieve is to display the actual key value (like, for example, the booking date), instead in my template I just see either colspan or booking_obj.

I already tried with something like:

{% for c, b in row.row_data.items %}
  <td colspan="">{{b}}</td> #This line just prints booking_obj
{% endfor %}

but it didn't work. Is there any way I can access the dict value properly?

CodePudding user response:

row_data is a list of dictionaries, so you access this with:

{% for data in row.row_data %}
    <td colspan="{{ data.colspan }}">{{ data.booking_obj }}</td>
{% endfor %}

Here data is thus a dictionary, and we access the corresponding values with data.colspan and data.booking_obj.

  • Related