我有这个表格:

class CSVImportForm(AuthorshipMixin, FormMixin, forms.Form):

    data = forms.FileField()

    def import_csv(self):
        school_csv = csv.DictReader(self.cleaned_data['data'])
        for row in school_csv:
            print(row)


import_csv()的预期目的是将CSV导入到应用程序的数据库中,但是为了简洁起见,已对其进行了更改。

当我尝试遍历school_csv时发生异常,我猜想是DictReader首次尝试读取文件时:

Traceback:
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/generic/edit.py" in post
  215.             return self.form_valid(form)
File "/opt/project/project/import/views.py" in form_valid
  16.         form.import_csv()
File "/opt/project/project/import/forms.py" in import_csv
  67.         for row in school_csv:
File "/usr/lib/python3.5/csv.py" in __next__
  109.             self.fieldnames
File "/usr/lib/python3.5/csv.py" in fieldnames
  96.                 self._fieldnames = next(self.reader)

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


我不相信我有机会选择打开文件的方式。我如何以文本模式打开,以便csv模块可以处理它?

我注意到InMemoryUploadedFile有一个file属性,该属性似乎很有用,但这是一个io.BytesIO对象。我想我可以做一些魔术,包括手动指定encoding.etc,但是我想这是Django可以简化的事情。

解决此问题的最佳方法是什么?

最佳答案

尝试使用

as_string = self.cleaned_data['data'].read().decode("utf-8")
school_csv = csv.DictReader(as_string)


如果期望str

from io import StringIO
school_csv = csv.DictReader(StringIO(as_string))


如果需要StringIO。

关于python - Django FileField不与Python 3的csv模块配合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40414219/

10-11 04:51