0

I want to upload an excel file to the server but I'm getting an error as MultiValueDictKeyError at ['document'] in the below mentioned code.

views.py

def index(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['document']
        print(uploaded_file.name)
        print(uploaded_file.size)
    return render(request, "polls/upload.html")

upload.html

<form  method="POST"  enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="file" name="document">
<button type="submit">Upload</button>
</form>

I want to be able to upload the file but I'm getting an error as MultiValueDictKeyError at ['document']. Can anyone please tell me what is wrong with the code?

newbie
  • 1
  • 1
  • Your code says "document" but your error message says "documents". Have you pasted a different version of your code by any chance? – Kent Shikama Nov 10 '19 at 23:59
  • @KentShikama Sorry, it was supposed to be ['document'] in the question too. – newbie Nov 11 '19 at 04:59
  • @KentShikama Do you know why the error is being raised? :/ – newbie Nov 11 '19 at 05:05
  • I don't see any issues as of now but feel free to post the results of `print(request.FILES)` right before you call `request.FILES['document']`. – Kent Shikama Nov 11 '19 at 08:28
  • @newbie you should be using `get` method of the `request.FILES` - `request.FILES.get('documents', None)`, I think this would work. – Giorgi Jambazishvili Nov 11 '19 at 09:27
  • @KentShikama This didn't work. Getting back the same error. – newbie Nov 11 '19 at 11:21
  • @GiorgiJambazishvili This doesn't work as well. Says "MultiValueDict has no attribute GET" :/ – newbie Nov 11 '19 at 11:36
  • @newbie I wasn't expecting it to work; I was hoping you would show us the output of that print statement. – Kent Shikama Nov 12 '19 at 00:32
  • @KentShikama def index(request): if request.method == 'POST': print(request.FILES) uploaded_file = request.FILES['document'] print(uploaded_file.name) print(uploaded_file.size) return render(request, "polls/upload.html") You mean like this? If yes, I don't see anything else except the error. Also, why are we using print statement before even calling request.FILES['document']? Please correct me if I'm wrong. – newbie Nov 12 '19 at 06:37
  • Yeah. Are you running this on a dev server or on something like wsgi; if the later, print statements won't show up. See https://stackoverflow.com/q/3543572/2750819 . Also can you show us more of your stacktrace? – Kent Shikama Nov 12 '19 at 19:49
  • @KentShikama I'm using Django development server. The stack trace: Request Method: POST Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.2.7 Exception Type: MultiValueDictKeyError Exception Value: 'document' – newbie Nov 15 '19 at 19:19
  • The print statement should show up in your stdout then. – Kent Shikama Nov 16 '19 at 02:16

0 Answers0