好的,我知道我有很多相同的问题,但我没有找到任何答案来解决我的问题。我是 Django 的新手,所以请记住。
我需要做一个从中上传文件的操作:
这是我的upload.py(这是一个views.py)
from django.http import HttpResponse
def upload(request)
viewfile = HttpResponse()
viewfile.write('''
<html>
<body>
<form action="/upload_done/" method="POST" enctype="multipart/form-data" {% csrf_token %}>
<label for="file">Filename:</label>
<input type="file" name="up_file" >
<br />
<input type="submit" name="submit" value="Submit" >
</form>
return HttpResponse(viewfile)
现在我的upload_done.py:
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse
import tempfile
import shutil
def upload_done(request):
viewfile = HttpResponse()
#####First I Tried this
Up_file = request.FILES['up_file']
""" It gives multivalue error('' 'up_file' '')
# then I change my upload.py input type file to text & try to collect information
# and change here Up_file = request.FILES['up_file'] to this
Up_file = request.POST['up_file']
现在我从 Django doc 收到 403 csrf 错误,我无法理解模板(只能理解 file.html 应该与 views.py 的函数名称相同的名称)是如何工作的。
请帮助我如何使用发布方法和如何上传文件。谢谢提前...
我也试过这样(写在/home/user/myproject/template/upload_form.html)(注意:模板目录可以正常工作)
<html>
<body>
<form action="/upload_done/" method="POST" enctype="multipart/form-data" {% csrf_token %}>
<label for="file">Filename:</label>
<input type="file" name="up_file" >
<br />
<input type="submit" name="submit" value="Submit" >
</form>
& 在上面的 2nd Views.py(即 upload_form.py)中,将 'Up_file = request.FILES['up_file']' 替换为此
if request.method == 'POST':
return render(request, 'upload_form.html',{})
但出现错误(必须返回 HttpResponse)