Django传递dataframe对象到前端网页

在django前端页面上展示的数据,还是使用django模板自带的语法

方式1 不推荐使用 直接使用 【df.to_html(index=False)】

使用to_html他会生成一个最基本的表格没有任何的样式,一点都不好看,如果有需要的话可以自行修改表格的样式,但博主觉得这样的方式太麻烦,

后端

python 复制代码
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)

前端

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

效果

方式2 推荐使用将df转为字典放到特定的表格下

这个表格是博主已经写好<table>有一定的样式了,这个方式就是将每一行数据给放到表格里面,相当于只是传递了数值。

下面的django模板语法能够动态的更新标题行和数据,数据表格有变动不需要修改前端模板

后端

python 复制代码
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)

前端

html 复制代码
<!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>

效果

相关推荐
西西弗Sisyphus6 分钟前
Python FastAPI 和 Uvicorn 同步 (Synchronous) vs 异步 (Asynchronous)
python·fastapi·uvicorn
MistaCloud8 分钟前
Pytorch深入浅出(十三)之模型微调
人工智能·pytorch·python·深度学习
菜的不敢吱声9 分钟前
swift学习第2,3天
python·学习·swift
AI小怪兽12 分钟前
基于YOLO11的航空安保与异常无人机检测系统(Python源码+数据集+Pyside6界面)
开发语言·人工智能·python·yolo·计算机视觉·无人机
百度地图汽车版14 分钟前
【AI地图 Tech说】第二期:一文解码百度地图ETA
前端
恋猫de小郭16 分钟前
罗技鼠标因为服务器证书过期无法使用?我是如何解决 SSL 证书问题
android·前端·flutter
Sailing18 分钟前
AI 流式对话该怎么做?SSE、fetch、axios 一次讲清楚
前端·javascript·面试
橙露24 分钟前
Vue3 组件通信全解析:技术细节、适用场景与性能优化
前端·javascript·vue.js
扉间79825 分钟前
lightrag嵌入思路
前端·chrome