Django raises MultiValueDictKeyError in File Upload
Modify Post method to
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
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