[英]Why file upload is not working in Django after directed from other url?
I want to do a simple web applications to let user to choose a task, where one of the tasks require file upload.我想做一个简单的网络应用程序,让用户选择一个任务,其中一个任务需要上传文件。 In home
, user is prompted to select task 1 or 2. After 2 is selected, it will enter another page to prompt user to upload file.在home
,提示用户选择任务 1 或 2。选择 2 后,将进入另一个页面提示用户上传文件。 I tried to follow a tutorial online for file upload but it does not work the way I wanted.我试图按照在线教程进行文件上传,但它没有按我想要的方式工作。
In views.py
, I have the following functions:在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')
For the urlpattern in urls.py
,对于urls.py
的urlpattern ,
urlpatterns=[
path('',views.home,name='home'),
path('choice',views.choice, name='choice'),
path('predict',views.predict,name='predict'),
]
The home.html
is to prompt user to select task: 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>
The predict.html
is the GUI to prompt user to upload file: 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>
So here is the question: When I directly access to http://127.0.0.1:8000/predict , after I have uploaded file, I can see document.name
and document.size
printed in the terminal as in predict function;那么问题来了:当我直接访问http://127.0.0.1:8000/predict 时,上传文件后,我可以看到终端中打印的document.name
和document.size
与 predict 函数中的一样; but when I choose a task from home
and being directed to predict
, I cannot see document.name
and document.size
printed.但是当我从home
选择一个任务并被引导到predict
,我看不到document.name
和document.size
打印出来。
Why is it so?为什么会这样?
in your views.py
在你的views.py
change :改变 :
name1=request.GET['name_1'] name2=request.GET['name_2']
to :到 :
name_1=request.GET['name1'] name_2=request.GET['name2']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.