如何在Django模板页面显示DataFrame?空白页问题求助
解决Django模板无法显示Pandas DataFrame数据的问题
问题原因
直接将Pandas DataFrame对象传入Django模板时,模板无法正确遍历行数据——默认遍历DataFrame只会拿到列名,若页面完全空白,大概率是数据传递格式不兼容,或是API返回的数据结构不符合预期。需要将DataFrame转换为模板可直接遍历的格式,比如字典列表。
修复步骤
1. 修改视图函数,转换DataFrame格式
把DataFrame转为records格式的字典列表,让模板能直接遍历每一行数据:
def index(request): import requests import pandas as pd url = "http://153.24.76.45:9000/abc/" response = requests.get(url) z = response.json() # 将DataFrame转为字典列表(每一行对应一个包含字段键值的字典) df = pd.DataFrame(z['Result']['LSData']) data_records = df.to_dict(orient='records') context = {'d': data_records} return render(request,'index.html',context)
2. 调整模板,遍历行数据并展示字段
根据你的实际数据字段,在模板里遍历每一行并输出对应内容(示例中替换为实际字段名即可):
<html> <head> <title>API Display</title> </head> <body> <h1>List of Data </h1> {% for row in d %} <div> <strong>字段1:{{ row.你的字段名1 }}</strong><br> <span>字段2:{{ row.你的字段名2 }}</span><br> <!-- 按需添加更多字段 --> </div> <hr> {% empty %} <p>暂无数据</p> {% endfor %} </body> </html>
额外排查点
- 先在视图函数中打印
z['Result']['LSData'],确认API返回的数据是有效的可转换结构(比如列表套字典)。 - 如果API返回数据格式异常,需先处理数据结构,确保能正常生成DataFrame。
内容的提问来源于stack exchange,提问作者Nazmeen Rauf
相关产品推荐
相关产品推荐

