在Django管理中上传文件时出现csv错误

时间:2019-05-07 11:54:53

标签: django

我正在通过admin上传文件,正在做一次小规模清洁工作并将数据保存在模型中。

所以在utils中,我有一个小功能

def _map_file_to_model(row):
    _into_product = {
        "qr_id": "",
        "ean": "",
        "description": "",
        "category": "",
        "marketing_text": "",
        "bullet": "",
        "brand_image": "",
        "image": ""
    }

    return {
        _into_product[key]: value
        for key, value in row.items()
    }

这是模型的表示。在管理员中,我正在这样做

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    change_list_template = 'product/products_blob.html'
    date_hierarchy = 'created_at'

    def get_urls(self):
        urls = super().get_urls()
        qr_urls = [
            path('import-file/', self.import_file, name='import-file'),
        ]
        return qr_urls + urls

    def import_file(self, request):
        if request.method == "POST":
            _file = request.FILES['text_file']
            reader = csv.reader(_file)

            self.message_user(request, "You're text file has been imported")
            _read_file = [_map_file_to_model(row) for row in reader]
            _product_model = _read_file
            Product.objects.bulk_create([
                Product(**data) for data in _product_model
            ])
        form = QrImportForm()
        payload = {"form": form}
        return render(
            request, 'product/text_form.html', payload
        )

和完整的Traceback

Traceback:

File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.7/contextlib.py" in inner
  74.                 return func(*args, **kwds)

File "/home/copser/Documents/Project/qr-backend/server/products/admin.py" in import_file
  36.             _read_file = [_map_file_to_model(row) for row in reader]

File "/home/copser/Documents/Project/qr-backend/server/products/admin.py" in <listcomp>
  36.             _read_file = [_map_file_to_model(row) for row in reader]

Exception Type: Error at /admin/products/product/import-file/
Exception Value: iterator should return strings, not bytes (did you open the file in text mode?)

所以有人可以帮我解释一下情况如何,我已经准备好上传文件,因此无需执行whit open...,但仍然可以。

1 个答案:

答案 0 :(得分:1)

您的request.FILES['text_file']是来自Django的UploadedFile,而不是文件内容。您需要调用csv.reader(_file.read())来读取上传的文件,然后再对其进行解析。