实现用户上传CSV与Django模型匹配并在HTML展示结果
我来帮你搞定这个CSV上传匹配数据库的需求!结合你给出的视图片段,咱们一步步完善整个逻辑:
1. 完善视图函数 check_fp
首先要确保导入必要的模块,然后在视图里处理上传的CSV文件,逐行读取并执行数据库匹配逻辑:
from django.shortcuts import render from django.db.models import Q import csv import io from .models import YourModel # 替换成你的实际模型类名 def check_fp(request): if not request.user.is_active: return render(request, 'your_login_page.html') # 替换成你的登录模板路径 match_results = [] # 存储每行的匹配结果数据 if request.method == 'POST' and request.FILES.get('csv_file'): uploaded_file = request.FILES['csv_file'] # 先验证文件格式是否为CSV if not uploaded_file.name.endswith('.csv'): return render(request, 'your_upload_template.html', {'error': '请上传标准CSV格式文件'}) # 读取并解析CSV内容 csv_content = uploaded_file.read().decode('UTF-8') csv_stream = io.StringIO(csv_content) next(csv_stream) # 跳过CSV表头(如果你的文件没有表头,就注释掉这行) for row in csv.reader(csv_stream, delimiter=','): if not row: # 跳过空行 continue target_item = row[0].strip() # 获取当前行的fp_Item值 # 执行模糊匹配查询 matched_record = YourModel.objects.filter(Q(fp_Item__contains=target_item)).first() # 构建结果字典:保留CSV原始值,匹配到则填充数据库字段,否则留空 result_row = { 'csv_item': target_item, 'db_field1': matched_record.your_field1 if matched_record else '', 'db_field2': matched_record.your_field2 if matched_record else '', # 继续添加你需要展示的其他数据库字段 } match_results.append(result_row) # 将结果传递给模板渲染 return render(request, 'your_result_template.html', {'results': match_results})
2. 编写结果展示的HTML模板
在模板里循环遍历结果列表,把匹配到的数据和原始CSV内容对应展示:
<!DOCTYPE html> <html> <head> <title>CSV匹配结果</title> <style> table { border-collapse: collapse; width: 80%; margin: 30px auto; } th, td { border: 1px solid #eee; padding: 10px; text-align: left; } th { background-color: #f5f5f5; font-weight: bold; } .upload-form { text-align: center; margin: 20px 0; } </style> </head> <body> <h2 style="text-align: center;">CSV与数据库匹配结果</h2> <!-- 上传表单(可放在同一页面或单独页面) --> <div class="upload-form"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="csv_file" accept=".csv" required> <button type="submit">上传并匹配</button> </form> </div> <!-- 展示匹配结果 --> {% if results %} <table> <thead> <tr> <th>CSV中的fp_Item</th> <th>数据库字段1</th> <th>数据库字段2</th> <!-- 添加你需要展示的其他表头 --> </tr> </thead> <tbody> {% for row in results %} <tr> <td>{{ row.csv_item }}</td> <td>{{ row.db_field1 }}</td> <td>{{ row.db_field2 }}</td> <!-- 对应添加其他字段的展示 --> </tr> {% endfor %} </tbody> </table> {% else %} <p style="text-align: center; color: #666;">暂无匹配结果,请上传CSV文件</p> {% endif %} </body> </html>
几个关键注意点
- 记得把代码里的
YourModel替换成你实际的Django模型类名,your_field1、your_field2替换成你需要从数据库获取的字段。 - 如果你的CSV文件没有表头,一定要注释掉视图里的
next(csv_stream)这行,不然会丢失第一行数据。 - 可以根据需求扩展错误处理逻辑,比如限制文件大小、处理编码异常等。
内容的提问来源于stack exchange,提问作者İlkem Çetinkaya
相关产品推荐
相关产品推荐

