[Fixed]-Django raises MultiValueDictKeyError in File Upload

21👍

You need to change multipart/form_data to multipart/form-data – that’s why request.FILES is empty: the form isn’t sending things in the way Django expects due to the typo. [EDIT: this has now been done]

Update 1: Also, rather than directly access request.FILES, try relying on the modelform’s default behaviour, as then it’ll have been handled as an upload appropriately. ie, newdoc = form.save() should do all you need, from a quick look at it – is there a particular reason you manually saving the file when the modelform can do that for you?

Update 2: Ah, look: you’re not assigning a name to your file upload element

From the docs:

HttpRequest.FILES A dictionary-like object containing all uploaded files. Each key in FILES is the name from the <input type="file" name="" />. Each value in FILES is an UploadedFile

So, you need to change

<input id="file" type="file" />

to

or, for default Django convention

<input id="id_docfile" type="file" name="docfile"/>

Indeed, it’s usually better to use the Django form to render the actual field, even if you’ve moved beyond the whole {{form.as_p}} approach:

{{form.docfile}}

PS. if you’ve not read them fully, I heartily recommend taking the time to go through all of the forms documentation

11👍

Modify Post method to

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}

0👍

For anymore who tried the above and still couldn’t figure out a solution. Here’s what I did:

views.py

if request.method == 'POST':
    doc = request.FILES #returns a dict-like object
    doc_name = doc['filename']
    ...

0👍

For anyone who tried the above and still couldn’t figure out a solution. Here’s what I did (2nd part):

if request.method == 'POST' and 'filename' in request.FILES:
    doc = request.FILES #returns a dict-like object
    doc_name = doc['filename']
    ...

Leave a comment