Django passes the dataframe object to the front-end web page

The data displayed on the django front-end page still uses the syntax that comes with the django template

Method 1 is not recommended to use  directly [df.to_html(index=False)]

        Using to_html will generate a basic form without any style, which is not good-looking at all. You can modify the style of the form if necessary, but the blogger thinks this method is too troublesome.

        rear end

df = pd.DataFrame({'Name': ['John', 'Alice', 'Smith'],
                           'Age': [30, 25, 35],
                           'City': ['New York', 'London', 'Paris']})

# 将DataFrame转换为HTML字符串
table_html = df.to_html(index=False)
    
# 将表格数据和其他数据打包成上下文对象
content= {
    'table_html': table_html
    }
return render(request, '自己的前端网页', content)

        front end

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <table>
        {
   
   { table_html | safe }}
    </table>
    <!-- 其他页面内容 -->
</body>
</html>

         Effect

        

Method 2  is recommended to  convert df into a dictionary and put it under a specific table

        This table is that the blogger has already written <table> with a certain style. This method is to put each row of data into the table, which is equivalent to just passing the value.

        The following django template syntax can dynamically update the header row and data, and there is no need to modify the front-end template if the data table changes

         rear end

df = pd.DataFrame({'Name': ['John', 'Alice', 'Smith'],
                           'Age': [30, 25, 35],
                           'City': ['New York', 'London', 'Paris']})
table_data = df.to_dict('records')
table_headers = df.columns.tolist()
content = {
    'table_headers':table_headers,
    'table_data': table_data
}
return render(request, '自己的前端网页', content)

        front end

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div class="table-responsive">
        <div id="example_wrapper" class="dataTables_wrapper">
            <table id="example" class="display table dataTable" role="grid"
                               aria-describedby="example_info">
                <thead>
                    <tr>
                        {% for header in table_headers %}
                            <th>{
   
   { header }}</th>
                        {% endfor %}
                        </tr>
                </thead>
                <tbody>
                    {% for row in table_data %}
                        <tr>
                            {% for value in row.values %}
                                 <td>{
   
   { value }}</td>
                            {% endfor %}
                        </tr>
                    {% endfor %}
                 </tbody>
            </table>
        </div>
    </div>
    <!-- 其他页面内容 -->
</body>
</html>

         Effect

Guess you like

Origin blog.csdn.net/gongzairen/article/details/132617475