[英]MultiValueDictKeyError for django image File upload

I have spent a LOT of time trying to resolve this- Read Django docs, consulted forms but not got anything satisfactory. So please be patient here with me. I am trying to do an upload of an Image file here from my html template. This is my html form

我花了很多時間試圖解決這個問題 - 閱讀Django文檔,咨詢表格但沒有得到任何滿意的結果。所以請耐心等待我。我試圖從我的html模板上傳一個圖像文件。這是我的html表單

<form id="tryOnPageForm" method="POST" enctype="multipart/form-data" action="/dummy/{{frame.slug}}/">
{% csrf_token %}
  <input type="file" name="uploadFromPC" id="uploadFromPC" class="myButton" title="Upload From PC" value= "Upload from PC" onchange="uploadPC()" style="float:left;">
 <input type="submit" id="Submit" class="myButton" value= "Done" style="display:none"><br><br>


The file upload happens properly an d I am able to see the uploaded image file in the HTML.


In my,


def upload_image(request, frameslug):

frame= VTryON.objects.get(slug=frameslug)
if request.method == 'POST':
    form = ImageUploadForm(request.POST, request.FILES)
    print "FILES", request.FILES
    if form.is_multipart():
        return HttpResponseRedirect('Successful')
        return HttpResponse('Invalid image')
    form = ImageUploadForm()
return render_to_response('dummy.html', {'form': form})

def save_file(file, path=''):
    ''' Little helper to save a file
    filename = file._get_name()
    fd = open('%s/%s' % (MEDIA_ROOT, str(path) + str(filename)), 'wb')
    for chunk in file.chunks():

and in my,


from django import forms
class ImageUploadForm(forms.Form):   
image = forms.ImageField(label='Select a file', help_text='max. 20 megabytes')

When I run my code I get this error


MultiValueDictKeyError at /dummy/fr1234/

The print statement in my from my shows this


FILES <MultiValueDict: {u'uploadFromPC': [<InMemoryUploadedFile: model4.jpg (image/jpeg)>]}>

and this is the traceback


File "C:\Python27\lib\site-packages\django\core\handlers\" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Work-Backup\LiClipse Workspace\vTryON_DJango_Integration\vTryON\" in upload_image
  189.             save_file(request.FILES['image'])
File "C:\Python27\lib\site-packages\django\utils\" in __getitem__
  301.             raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /dummy/fr1234/
Exception Value: "'image'"

I am aware that the enctype should be multipart/form-data since I have read it in tutorials. ALso, i have not used any field in my to store the uploaded image.Instead I want to directly save it to thr MEDIA_URL location.Might that be an issue? Please help. This has held me up for a long time. Thanks in advance.

我知道enctype應該是multipart / form-data,因為我已經在教程中閱讀了它。另外,我沒有在models.py中使用任何字段來存儲上傳的圖像。相反,我想直接將它保存到thrIA MEDIA_URL location.Might那是一個問題嗎?請幫忙。這讓我很長時間了。提前致謝。

2 个解决方案



I was able to solve this(after spending a lot of time and with some help from my friends...)


I think the error


Exception Type: MultiValueDictKeyError at /dummy/fr1234/ Exception Value: "'image'"

異常類型:/ dummy / fr1234處的MultiValueDictKeyError /異常值:“'image'”

was coming because request.FILES was unable to get the uploaded image from the user input, the reason being that the name of the user input file that I provided was wrong!!


It should have been request.FILES['uploadFromPC'] instead of request.FILES['image'] because that is the name that I had kept in my HTML.

應該是request.FILES ['uploadFromPC']而不是request.FILES ['image'],因為這是我在HTML中保留的名稱。

<input type="file" name="uploadFromPC" id="uploadFromPC" class="myButton" title="Upload From PC" value= "Upload from PC" onchange="uploadPC()" style="float:left;">

That was a stupid error and a lot of time wasted to fix it.. :(

這是一個愚蠢的錯誤,浪費了很多時間來修復它.. :(

.. but ya, good learning.


I hope this helps somebody else who is trying to do something similar. Although, I would like it if somebody can explain to me the use of here. Is it possible to do an user upload without




I found that the error occurs when you submit the form without selecting the file. when a file is not selected then the input_name in your case image is u''. this gives the error as the dictionary has no such key.
i tried to find a way to try and except error but there is no such exception in python MultiValueDictKeyError

我發現在沒有選擇文件的情況下提交表單時會發生錯誤。如果未選擇文件,則案例圖像中的input_name為u''。這給出了錯誤,因為字典沒有這樣的鍵。我試圖找到一種方法來嘗試除了錯誤,但在python MultiValueDictKeyError中沒有這樣的異常



粤ICP备14056181号  © 2014-2021