You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取字典列表JSON数据并在HTML展示GLI Code/Country列表格

Django模板表格布局修正方案

问题描述

已通过Django视图从DBFS读取CSV数据,转为字典列表格式传递给HTML模板,但原模板代码无法生成预期的表格布局,需要实现每行展示一条数据的GLI Code和Country信息,对应到表格的两列中。

修正后的HTML模板代码

<thead>
  <tr>
    <th>GLI Code</th>
    <th>Country</th>
  </tr>
</thead>
<tbody>
  {% for item in data %}
  <tr>
    <td>{{ item.GLI Code }}</td>
    <td>{{ item.Country }}</td>
  </tr>
  {% endfor %}
</tbody>

如果需要动态适配列名变化(无需硬编码表头),可使用以下代码替换表头部分:

<thead>
  <tr>
    {% if data %}
      {% for key in data.0.keys %}
        {% if key != 'index' %}
          <th>{{ key }}</th>
        {% endif %}
      {% endfor %}
    {% endif %}
  </tr>
</thead>

原代码问题分析

  1. 表头逻辑错误:原代码循环整个data列表(每个元素是字典),直接输出字典对象作为表头,导致显示的是字典字符串而非实际列名。
  2. 表体结构错误:原代码尝试访问data.GLICode,但data是列表而非单个字典,无法直接获取字段值;同时把所有GLI Code集中在一行、所有Country集中在另一行,完全不符合每行一条数据的展示需求。

视图代码优化建议(可选)

原视图中df.reset_index()会在数据中加入不必要的index字段,可去掉该步骤简化数据结构:

def tables_data(request):
    dbfs_source_file_path = 'dbfs:/mnt/adls/MPF/Alternate_Currency_Keys_Aug.csv'
    local_file_download_path = './mpf_dataset.csv'
    dbfs_api  = DbfsApi(api_client)
    dbfs_path = DbfsPath(dbfs_source_file_path)
    dbfs_api.get_file(dbfs_path, local_file_download_path, overwrite = True)
    df = pd.read_csv(local_file_download_path).head(5)
    # 移除reset_index(),直接生成不含index字段的字典列表
    json_records = df.to_json(orient='records')
    data = json.loads(json_records)
    return render(request, "home/tables-data.html", {'data':data})

内容的提问来源于stack exchange,提问作者Satyajit Barik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:35:32