0

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) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]

1 Answer 1

1

It looks OK. I believe you just need to replace field with data :

column_data = [{"data": val, "title": val} for val in df.columns.values]
                 ^^^^

columns.data specify the object property / source.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Still waiting to test this, will accept when I verify!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.