我正在尝试添加一个选项来为我的 Django 应用程序中的一个模型上传 CSV 文件。我关注了this tutorial设置它但无法让它工作。上传文件时出现以下错误:
“_csv.Error:迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?)”
这是我尝试上传的文件示例:
https://pastebin.com/DMyudHav
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/