Django图片上传触发MultiValueDictKeyError错误,求解决方案
Django图片上传触发MultiValueDictKeyError('image')的解决方法
问题场景
使用Django实现图片上传功能,已编写views.py、HTML模板及ProfileForm表单类,但上传图片时触发MultiValueDictKeyError,错误提示键'image'不存在。
相关代码
views.py
# Create your views here. def store_file(file): with open("temp/mensschappy.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "profiles/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): store_file(request.FILES["image"]) return HttpResponseRedirect("/profiles") return render(request, "profiles/create_profile.html", { "form": submitted_form })
HTML模板
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" href="{% static "profiles/styles.css" %}"> </head> <body> <form action="/profiles/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button>Upload!</button> </form> </body> </html>
ProfileForm
from django import forms class ProfileForm(forms.Form): upload_file = forms.FileField()
错误信息
MultiValueDictKeyError at /profiles/ 'image' Request Method: POST Request URL: http://127.0.0.1:8000/profiles/ Django Version: 4.1.1 Exception Type: MultiValueDictKeyError Exception Value: 'image' Exception Location: C:\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in __getitem__ Raised during: profiles.views.CreateProfileView Python Executable: C:\Python310\python.exe Python Version: 3.10.6 Python Path: ['C:\Users\engel\Documents\NVWA\software\blockchainfruit\schoolfruitnvwa', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Thu, 06 Oct 2022 08:38:50 +0000
问题原因
表单类ProfileForm中定义的文件字段名为upload_file,但视图CreateProfileView的post方法中,尝试从request.FILES中获取键为image的文件,两者名称不匹配,导致找不到对应键,触发MultiValueDictKeyError。
解决方法
只需保证表单字段名与视图中调用的键名一致,有两种方案可选:
方案一:修改视图中的键名,匹配表单字段
将views.py中store_file(request.FILES["image"])改为:
store_file(request.FILES["upload_file"])
方案二:修改表单字段名,匹配视图中的键
将ProfileForm中的字段名改为image:
from django import forms class ProfileForm(forms.Form): image = forms.FileField()
更规范的写法:使用表单清理后的数据
推荐通过表单的cleaned_data获取上传文件,无需直接操作request.FILES,代码更健壮且易于维护:
if submitted_form.is_valid(): store_file(submitted_form.cleaned_data["upload_file"]) # 或对应修改后的字段名image return HttpResponseRedirect("/profiles")
内容的提问来源于stack exchange,提问作者mightycode Newton
相关产品推荐
相关产品推荐

