【问题标题】:How to fix "Iterators should return strings, not bytes" in Django File Upload [duplicate]如何修复 Django File Upload 中的“迭代器应该返回字符串,而不是字节”[重复]
【发布时间】:2020-01-10 14:14:31
【问题描述】:

我正在尝试为我的 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 上运行应用程序,这可能是原因吗?

【问题讨论】:

  • 请发布完整的回溯

标签: python django csv file-upload


【解决方案1】:

查看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.

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 2013-04-21
    • 1970-01-01
    • 2017-01-29
    • 2023-01-22
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多