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

Django循环仅显示最后一行:CSV上传至文件系统HTML展示异常

解决CSV文件上传后仅显示最后一行的问题

嗨,这问题我太熟了——你这明显是变量覆盖导致的!虽然代码确实遍历了整个CSV,但每次循环都把line变量重新赋值成当前行,最后传到模板里的自然只有最后一行的数据。咱们马上来修复它:

第一步:修改视图函数,收集所有CSV行

你需要把每一行数据都存到一个列表里,而不是每次覆盖单个变量。修改后的代码大概是这样:

import csv  # 别忘了导入csv模块!
from django.core.files.storage import FileSystemStorage
from django.contrib import messages

def check_fp(request):
    if not request.user.is_active:
        return render(request, 'login.html')
    
    csv_rows = []  # 初始化空列表,用来存所有CSV行
    if request.method == 'POST' and request.FILES.get('csv_file2'):
        myfile = request.FILES['csv_file2']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        
        # 读取并解析CSV文件
        with fs.open(filename, 'r', encoding='utf-8') as f:
            csv_reader = csv.reader(f)
            for line in csv_reader:
                messages.add_message(request, messages.INFO, line)
                csv_rows.append(line)  # 把每一行追加到列表里
    
    # 把完整的行列表传给模板
    return render(request, '你的模板文件名.html', {'csv_rows': csv_rows})

第二步:修改模板,循环展示所有行

现在模板里要遍历咱们传过去的csv_rows列表,而不是单个line变量。比如用表格展示的话:

{% if csv_rows %}
    <div class="csv-display">
        <table border="1">
            {% for row in csv_rows %}
                <tr>
                    {% for cell in row %}
                        <td>{{ cell }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </table>
    </div>
{% else %}
    <p>还没有上传CSV文件哦~</p>
{% endif %}

额外小提示

  1. 如果你的CSV文件有表头行,可以单独提取出来,比如:

    with fs.open(filename, 'r', encoding='utf-8') as f:
        csv_reader = csv.reader(f)
        header = next(csv_reader)  # 获取第一行作为表头
        csv_rows.append(header)
        for line in csv_reader:
            csv_rows.append(line)
    

    然后在模板里给表头加个样式区分。

  2. 如果CSV文件编码不是UTF-8(比如GBK),打开文件时要指定编码:with fs.open(filename, 'r', encoding='gbk') as f:

这样修改后,页面就能完整展示CSV里的所有内容啦!

内容的提问来源于stack exchange,提问作者İlkem Çetinkaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:09:35