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>

效果

相关推荐
槑槑紫几秒前
pytorch(gpu版本安装)
人工智能·pytorch·python
知识中的海王1 分钟前
猿人学web端爬虫攻防大赛赛题第15题——备周则意怠-常见则不疑
爬虫·python
专注VB编程开发20年6 分钟前
jss html5-node.nodeType 属性用于表示节点的类型
前端·js
小白学大数据9 分钟前
如何避免爬虫因Cookie过期导致登录失效
开发语言·爬虫·python·scrapy
测试老哥20 分钟前
接口测试和功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·测试用例·接口测试
烛阴1 小时前
Promise无法中断?教你三招优雅实现异步任务取消
前端·javascript
GUIQU.1 小时前
【Vue】单元测试(Jest/Vue Test Utils)
前端·vue.js
小白学大数据1 小时前
Python自动化解决滑块验证码的最佳实践
开发语言·python·自动化
暮乘白帝过重山1 小时前
Ollama 在本地分析文件夹中的文件
前端·chrome·ollama
Albert Edison1 小时前
Python入门基础
开发语言·python