I am using Django 4.0 to display a frontend page which source data is a list of dict. I want to order the keys of the dict and then display all dict in the list in the same order. Here is my views.py:
def UserGoalstatus(request, promise_token):
print("__UserGoalstatus__")
from cmd_utils import Retrieve_goal
data = Retrieve_goal(promise_token)
keys = set()
for item in data:
keys.update(set(item))
key_order = sorted(keys)
context = {
"data": data,
"key_order": key_order,
}
return render(request, 'json_table.html', context)
Here is the content of my 'data' variable:
[
{'goal_key': '286815', 'goal_type': 'hotelreservation', 'goal_id': 16149845, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:34', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}},
{'goal_key': '1208107', 'goal_type': 'hotelreservation', 'goal_id': 16149846, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:35', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}}
]
Here is my html file which I would like to print all content in data in the order of 'key_order'
<table id="dtBasicExample" class="table table-hover table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
{% for key in key_order %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
{% for key in key_order %}
<td>{{ item.get(key) }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
This part seems not right :{{ item.get(key) }} , anyone can suggest the right way to access the value mapping to the specific key ?