Skip to content

Open In Colab

Django Pandas DataFrame to jQuery DataTable

DataTables (https://datatables.net/) is a cool jQuery Javacript plugin to show advanced tables, an easy way.

Define the View

Table classe can be set with parameter classes, to be used with Bootstrap for example.

df.to_html(table_id="table_example", classes=["table-bordered", "table-striped", "table-hover"])
import pandas as pd
import numpy as np
import requests
from django.shortcuts import render

def datatable_view(request):
    dates = pd.date_range('2022-01-01', '2022-01-10')
    df = pd.DataFrame({
        'date': dates,
        'sales': np.round(np.random.rand(len(dates))*1000)
    })
    # table classes, if needed (ex: Bootstrap)
    # classes=["table-bordered", "table-striped", "table-hover"]
    table_data = df.to_html(table_id="table_example")
    context = {'table_data': table_data}
    return render(request, "app/datatable.html", context)

Define the Template

Define the template app/datatable.html.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- datatables CSS -->
    <link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css">
</head>

<body id="page-top">
    <!-- DataTable content -->
    <div class="card-body">
        {{ table_data | safe }}
    </div>

    <!-- datatables JS -->
    <script type="text/javascript"src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript"src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script>
        {% comment %} Initialize DataTable {% endcomment %}
        $(document).ready(function() {
            $('#table_example').DataTable();
        } );
    </script>
</body>

</html>