【问题标题】:Load CSV file in Django view and turn into HTML table在 Django 视图中加载 CSV 文件并转换为 HTML 表
【发布时间】:2020-07-07 00:27:30
【问题描述】:

我有这个查看代码

def datatable(request, file):
    csv_fp = open(f'data/{file}.csv', 'r')
    reader = csv.DictReader(csv_fp)
    headers = [col for col in reader.fieldnames]
    out = [row for row in reader]
    return render(request, 'datatable.html', {'data' : out, 'headers' : headers})

这是我的模板

<table id="table" class="display" style="width: 100%;">
  <thead>
    <tr>
      {% for header in headers%}
      <th>{{ header }}</th>
      {% endfor %}
    </tr>
  </thead>
  <tbody>
    <tr>
      {% for row in out%}
      <td>{{row}}</td>
      {% endfor %}
    </tr>
  </tbody>
</table>

我正在尝试将此 CSV 转换为我的 Django 模板中的表格。标题已正确完成,但行已关闭。有没有更好的方法来读取行,以便更容易进入 tbody?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的问题似乎是 {% for row in out %},您正在传递 {'data' : out}

    试试:

    <table id="table" class="display" style="width: 100%;">
      <thead>
        <tr>
          {% for header in headers %}
          <th>{{ header }}</th>
          {% endfor %}
        </tr>
      </thead>
      <tbody>
        <tr>
          {% for row in data %}
          <td>{{ row }}</td>
          {% endfor %}
        </tr>
      </tbody>
    </table>
    

    【讨论】:

      猜你喜欢
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多