python - 如何修复 Django 文件上传中的 "Iterators should return strings, not bytes"

标签 python django csv file-upload

我正在尝试添加一个选项来为我的 Django 应用程序中的一个模型上传 CSV 文件。我关注了this tutorial设置它但无法让它工作。上传文件时出现以下错误:

“_csv.Error:迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?)”

这是我尝试上传的文件示例:
https://pastebin.com/DMyudHav

我已经尝试过以下答案:
How can I handle the error "expected str, bytes or os.PathLike object, not InMemoryUploadedFile' in Python or Django?

Getting a TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile

我的代码现在看起来像这样:

import csv
...

class AttendantsCSVForm(forms.Form):
    event = forms.ModelChoiceField(queryset=Event.objects.all(), required=False)
    csv_file = forms.FileField()


class PersonAdmin(admin.ModelAdmin):
    def import_csv(self, request):
        if request.method == 'POST':
            form = AttendantsCSVForm(request.POST, request.FILES)
            if form.is_valid():
                event_id = request.POST.get('event')
                csv_file = request.FILES['csv_file']
                reader = csv.reader(csv_file)
                for row in reader:  # the error occurs here
                    for text in row:
                        print(text)
                self.message_user(request, _('CSV file imported successfully.'))
        form = AttendantsCSVForm()
        payload = {'form': form}
        return render(request, 'admin/attendants_csv_form.html', payload)

我该如何解决这个问题?我也阅读了 python 的 csv 文档,但仍然找不到这个问题的解决方案。

我在 Windows 上运行该应用程序,这可能是原因吗?

最佳答案

检查Link了解更多信息。

我想 Jibu James 的答案会起作用。

file = request.FILES['file'] 
decoded_file = file.read().decode('utf-8').splitlines()
reader = csv.DictReader(decoded_file)
for row in reader:
    # Get each cell value based on key-value pair. 
    # Key will always be what lies on the first row.

关于python - 如何修复 Django 文件上传中的 "Iterators should return strings, not bytes",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57843385/

相关文章:

SQL:将连接表的 id 聚合成一个字符串

python - 测试函数在 python 中返回可迭代

python - 使用二进制数据将固定宽度文件读取到 Pandas 中

django - 如何将stripe payment与现有的django表单集成,并且仅在付款成功时保存表单

python - 使用 Django 时,Pylint 不会报告错误的导入顺序

python - 如何从一行之间删除换行符而不从行尾删除换行符python?

Python从列表列表中删除空元素

python - Unicode 字符另存为 ?在 MySQL SQLAlchemy 中(警告 : Incorrect string value)

python - 在数据框中的其他列上使用应用函数的新列

django - 在 Docker 中安装地理空间库