2

I'm trying to add an option to upload CSV files for one of my models in my Django App. I followed this tutorial to set it up but couldn't get it working. When uploading the file I get the following error:

"_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)"

This is a sample of the file I'm trying to upload:
https://pastebin.com/DMyudHav

I have already tried the following answers:
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

My code looks like this right now:

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)

How can I solve this? I've also read python's csv documentation but still can't find a solution to this problem.

I'm running the app on Windows, could that be the cause?

angardi
  • 367
  • 3
  • 14

1 Answers1

4

Check the Link for more information.

I guess Jibu James's answer would work.

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.
Shawn Lee
  • 74
  • 5