I am looking for a reusable and straightforward solution to render a valid JSON object as an HTML table using Django. The flow is as follows:
Views.py
from utils load get_data_frame
class MyView(TemplateView):
template_name = "my_template.html"
df = get_data_frame()
column_data = [{"field": val, "title": val} for val in df.columns.values]
json_object = df.to_json(orient='records')
context['json_data'] = json_object
context['columns'] = column_data
my_template.html
<script>
var my_data = {{ json_data|safe }};
var column_data = {{ columns|safe }};
$( function() {
$( "#my-cool-table" ).dataTable(
{
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
"data": my_data,
"columns": column_data,
});
});
</script>
{% if json_data %}
<table id="my-cool-table">
<thead>
</thead>
<tbody>
</tbody>
</table>
{% else %}
However, when I render this template the columns show up without issue but the data of the table only renders the default values "-" specified in defaultContent. Am I missing an argument for dataTables? Or is the <script> tag in the wrong location?
When I print the variable my_data in the Firefox console it comes up in the format:
Array(17) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]