From 38ec8060c07e8e335f4a82f8b766d8b201277bd2 Mon Sep 17 00:00:00 2001 From: sichan Date: Fri, 14 Jun 2024 01:48:24 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=9A=E7=94=A8excel=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E6=9C=89bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/views.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/common/views.py b/common/views.py index 95f1e80..08663aa 100644 --- a/common/views.py +++ b/common/views.py @@ -3,8 +3,6 @@ import os import urllib.parse import openpyxl -from openpyxl.utils import get_column_letter -from openpyxl.worksheet.datavalidation import DataValidation from django.apps import apps from django.core.exceptions import ValidationError from openpyxl import load_workbook @@ -14,8 +12,7 @@ from django.contrib.auth.decorators import login_required from django.contrib.staticfiles import finders from django.core.files.storage import default_storage from django.http import FileResponse, HttpResponseNotFound, JsonResponse -from django.views.decorators.csrf import csrf_exempt, csrf_protect -from rest_framework.decorators import api_view +from django.views.decorators.csrf import csrf_protect from rest_framework.serializers import ModelSerializer @@ -127,11 +124,11 @@ def common_excel_parse(request): file_name = default_storage.save(excel_file.name, excel_file) file_path = os.path.join(settings.MEDIA_ROOT, file_name) - def create_dynamic_serializer(mod): + def create_dynamic_serializer(mod, include): class DynamicSerializer(ModelSerializer): class Meta: model = mod - fields = '__all__' + fields = include return DynamicSerializer @@ -158,6 +155,7 @@ def common_excel_parse(request): # 创建一个映射,将Excel表头映射到模型字段名 header_to_field_map = {header: fields_map_nf[header] for header in header_row} + header_fields = [header_to_field_map[header] for header in header_row] for row in sheet.iter_rows(min_row=2, values_only=True): if not all(value is None for value in row): @@ -171,7 +169,7 @@ def common_excel_parse(request): return JsonResponse({'error': f'数据校验错误: {e.message_dict}'}, status=400) # 动态获取序列化器 - serializer_class = create_dynamic_serializer(model) + serializer_class = create_dynamic_serializer(model, include=header_fields) serializer = serializer_class(data, many=True)