我想做一个简单的网络应用程序让用户选择一个任务,其中一个任务需要文件上传。在home中,提示用户选择任务 1 或 2。选择 2 后,将进入另一个页面提示用户上传文件。我尝试按照在线教程进行文件上传,但它没有按我想要的方式工作。
在views.py中,我有以下功能:
def home(request):
return render(request,'home.html')
def choice(request):
name_1=request.GET['name_1']
name_2=request.GET['name_2']
if request.GET['choice']=='1':return render(request, "train.html",{"name_1":name_1, "name_2":name_2})
elif request.GET['choice']=='2':return render(request, "train.html",{"name1":name_1, "name2":name_2})
def predict(request):
if request.method=="POST":
document=request.FILES['document']
print(document.name)
print(document.size)
return render(request,'predict.html')
对于 中的urlpattern,urls.py
urlpatterns=[
path('',views.home,name='home'),
path('choice',views.choice, name='choice'),
path('predict',views.predict,name='predict'),
]
这home.html是提示用户选择任务:
<h2>Select a Task:</h2>
<form action="choice">
<select name="choice">
<option value="1" selected >Train new model</option>
<option value="2" >Prediction</option>
</select>
<br><br>
System 1 is used to predict system 2 <br>
Enter the name of system 1:<br>
<input type="text" name="name_1"><br>
Enter the name of system 2:<br>
<input type="text" name="name_2"><br>
<input type="submit"></form><br><br>
</form>
这predict.html是提示用户上传文件的 GUI:
<br><h3>{{name_1}} is used to predict {{name_2}}</h3>
Upload profiler logs:<br>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="document"><br><br>
<button type="submit">Upload file</button>
</form>
那么问题来了:当我直接访问http://127.0.0.1:8000/predict时,上传文件后,我可以在终端中看到document.name并document.size打印出预测功能;但是当我从中选择任务home并被定向到时predict,我看不到document.name和document.size打印。
为什么会这样?