问题描述
我在设置此 Django Web 应用程序时遇到错误。每当我点击提交按钮时,我都会收到 505 错误消息。图像应该保存在根目录中,但我似乎无法弄清楚问题。
以下是网络应用程序的代码
urls.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from CancerClassifier import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/',admin.site.urls),url('^$',views.index,name = 'homepage'),url('predictimage',views.predictimage,name='predictimage'),]
urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
views.py:
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
def index(request):
context = {'a' : 1}
return render(request,'index.html',context)
def predictimage(request):
print(request)
print(request.POST.dict())
fileObj = request.FILES['filePath']
fs = FileSystemStorage()
fs.save(fileObj.name,fileObj)
context = {'a' : 1}
return render(request,context)
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<Meta charset="utf-8">
<title>Skin Lesion Classifier</title>
</head>
<body>
<h1>Upload new File</h1>
<form class="imageUpload" action="predictimage" method="post">
{% csrf_token %}
<input type="file" name="filePath">
<input type="submit" value="Submit">
<br>
<h3>Prediction: {{prediction}}</h3>
</form>
</body>
</html>
这是我在终端收到的错误信息:
[16/Jan/2021 17:13:14] "GET / HTTP/1.1" 200 493
<WsgiRequest: POST '/predictimage'>
{'csrfmiddlewaretoken': 'UPYALDxVQ8SJR8DDy55h14PnaaWElXBwcYnlms6hhpV9qgbtdy1hW6UnU1Y8TVpk','filePath': 'image-asset.jpeg'}
Internal Server Error: /predictimage
Traceback (most recent call last):
File "/Users/sparshbohra/opt/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py",line 76,in __getitem__
list_ = super().__getitem__(key)
KeyError: 'filePath'
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "/Users/sparshbohra/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py",line 47,in inner
response = get_response(request)
File "/Users/sparshbohra/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py",line 181,in _get_response
response = wrapped_callback(request,*callback_args,**callback_kwargs)
File "/Users/sparshbohra/cancer-scanner/CancerProj/CancerClassifier/views.py",line 12,in predictimage
fileObj = request.FILES['filePath']
File "/Users/sparshbohra/opt/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py",line 78,in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'filePath'
[16/Jan/2021 17:13:19] "POST /predictimage HTTP/1.1" 500 67980
解决方法
原来我只是缺少 HTML 表单中的 enctype。
刚刚添加 enctype="multipart/form-data" 在表单标签中