Tahu
Tahu

Reputation: 3

Parse and process CSV in Django

Apologies in advance since I'm new to Django (and I've also had to freshen up my Python skills). I'm trying to make a simple example of uploading a file through a form and then printing the rows in my terminal (as a test before doing some actual processing). My views.py contains the following:

def upload_csv(request):
    if "GET" == request.method:
        return render(request, "portal/csvupload.html")
    csv_file = request.FILES["csv_file"]
    handle_files(csv_file)
    return HttpResponseRedirect(reverse("portal:csvupload"))

def handle_files(csvfile):
    csv_reader = csv.reader(csvfile)
    for line in csv_reader:
        print(line)

Now this returns an error message saying "expected str, bytes or os.PathLike object, not InMemoryUploadedFile", and I'm unsure what's wrong with the code based on the error message? From a Python perspective it looks fine I think, but perhaps it's something to do with the re-direct? Apperciate all answers

Upvotes: 0

Views: 463

Answers (1)

J. Owens
J. Owens

Reputation: 852

request.FILES["csv_file"] is returning an InMemoryUploadedFile object and csv.reader does not know how to handle such an object. I believe you need to call the object's read method: handle_files(csv_file.read()). Note the warning in the documentation: "Be careful with this method: if the uploaded file is huge it can overwhelm your system if you try to read it into memory. You’ll probably want to use chunks() instead; see below."

Upvotes: 1

Related Questions