【发布时间】:2014-07-30 10:38:44
【问题描述】:
我花了很多时间试图解决这个问题——阅读 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>
</form>
文件上传正常,我可以在 HTML 中看到上传的图像文件。
在我的views.py,
def upload_image(request, frameslug):
frame= v.objects.get(slug=frameslug)
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
print "FILES", request.FILES
if form.is_multipart():
save_file(request.FILES['image'])
return HttpResponseRedirect('Successful')
else:
return HttpResponse('Invalid image')
else:
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():
fd.write(chunk)
fd.close()
在我的forms.py,
from django import forms
class ImageUploadForm(forms.Form):
image = forms.ImageField(label='Select a file', help_text='max. 20 megabytes')
当我运行我的代码时,我得到了这个错误
MultiValueDictKeyError at /dummy/fr1234/
my from my view.py 中的 print 语句显示了这一点
FILES <MultiValueDict: {u'uploadFromPC': [<InMemoryUploadedFile: model4.jpg (image/jpeg)>]}>
这是回溯
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Work-Backup\LiClipse Workspace\vTryON_DJango_Integration\vTryON\views.py" in upload_image
189. save_file(request.FILES['image'])
File "C:\Python27\lib\site-packages\django\utils\datastructures.py" in __getitem__
301. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /dummy/fr1234/
Exception Value: "'image'"
我知道 enctype 应该是 multipart/form-data,因为我已经在教程中阅读过它。另外,我没有使用 models.py 中的任何字段来存储上传的图像。相反,我想直接将其保存到 MEDIA_URL 位置。这可能是个问题吗?
请帮忙。这让我坚持了很长时间。提前致谢。
【问题讨论】:
标签: python file-upload django-forms django-views