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

Django导出CSV仅输出第一行数据 全量导出代码问题排查求助

问题原因

  1. 核心故障点在views.py的export_csv函数逻辑:你将response['Content-Disposition']响应头配置写在了遍历数据库数据的for循环内部,每次写入一行数据都会覆盖响应头配置,最终导致只有表头和第一行数据能正常写入导出文件。
  2. 额外存在前端显示异常问题:HTML表格的表头和表体字段顺序不匹配,不过该问题不影响CSV导出功能,仅会导致页面展示的字段错位。

修复代码

修复后views.py的export_csv函数

def export_csv(request):
    response = HttpResponse(content_type='text/csv')
    # 响应头配置移到循环外,全局仅需设置一次
    response['Content-Disposition'] = 'attachment; filename="Expenses.csv"'

    writer = csv.writer(response)
    writer.writerow(['User', 'Account Number', 'Price', 'Date'])

    for file in account.objects.all().values_list('User', 'Account_Number', 'Price', 'Date'):
        writer.writerow(file)
    return response

可选:修复前端表格字段错位问题

将HTML表格的表体部分修改为和表头对应的字段顺序:

<tbody>
        {% for item in slist%}
    <tr>
        <td>{{item.User}}</td>
        <td>{{item.Account_Number}}</td>
        <td>{{item.Price}}</td>
        <td>{{item.Date}}</td>
    </tr>
        {% endfor %}
</tbody>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:27:00