0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Render dataframe as AgGrid table within html

Posted at

Render dataframe as AgGrid table in html

You have view function like below

def view_positions_specs(request):
    specsdf=get_positions_specs()
    specsdf=convert_columns_to_str(specsdf)
    return render(request,"datatable_aggrid.html",{"title":"Positions Specs", "data":specsdf.to_dict(orient="records")})

You are passing dataframe as list of dictionaries, where each dictionary represents a record in a table with consistent keys.

Below is how datatable_aggrid.html looks like

{% extends "layout.html" %}

{% block extra_css %}
<!-- ag-Grid CSS -->
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/styles/ag-theme-material.css">
{% endblock %}

{% block title %}{{title}}{% endblock %}

{% block content %}
<h2 class="mb-4">{{ title }}</h2>
<!-- ag-Grid container -->
<div id="myGrid" class="ag-theme-material" style="height: 700px; width: 100%;"></div>

<!-- ag-Grid JS -->
<script src="https://unpkg.com/ag-grid-community@31.0.1/dist/ag-grid-community.min.js"></script>

<script>

    // Django JSON Data (Rendered from View)
    var rowData = {{ data | safe }};

    console.log(`data is ${JSON.stringify(rowData)}`)


    const columnDefs = Object.keys(rowData[0]).map((columnName)=>({headerName:columnName, field:columnName, filter: "agTextColumnFilter"}))
    // Grid Options
    var gridOptions = {
        columnDefs: columnDefs,
        rowData: rowData,
        pagination: true
    };

    // Initialize ag-Grid
    document.addEventListener('DOMContentLoaded', function () {
        var gridDiv = document.querySelector("#myGrid");
        //new agGrid.Grid(gridDiv, gridOptions);
        const gridApi = agGrid.createGrid(gridDiv, gridOptions);
    });
</script>

{% endblock %}

Hope above helps!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?