Python 在django中上载图像
我正在为一个网站编写一个简单的文件上传程序。用户看到一个表单:Python 在django中上载图像,python,django,error-handling,image-uploading,Python,Django,Error Handling,Image Uploading,我正在为一个网站编写一个简单的文件上传程序。用户看到一个表单: <form action="/user_profileform/" method="POST" enctype="multipart/form-data" name="uform" id="userform">{% csrf_token %} {{form}} <input type="submit" value="submit" name="usubmit"> </form> 当我尝试此功能
<form action="/user_profileform/" method="POST" enctype="multipart/form-data" name="uform" id="userform">{% csrf_token %}
{{form}}
<input type="submit" value="submit" name="usubmit">
</form>
当我尝试此功能时,总会出现异常:
/user\u profileform处的IOError/
[Errno 21]是一个目录:'/home/ghrix/ghrixbidding/media/images/',因为settings.media\u ROOT是一个目录。您需要为句柄提供文件名。
最好将模型与文件字段一起使用,因为它会自动在介质中生成唯一的文件名。您试图打开的
settings.MEDIA\u ROOT
中描述了它。MEDIA\u ROOT是目录。MEDIA ROOT是在settings.py MEDIA\u ROOT='/home/ghrix/ghrixbidding/MEDIA/images/'中定义的,当我尝试打开此目标时('/home/ghrix/ghrixbidding/static/MEDIA',',wb+'),它将显示:-IOError at/user\u profileform/[Errno 21]是一个目录:'/home/ghrix/ghrixbidding/static/media',当我尝试此destination=open('/home/ghrix/ghrixbidding/static/media',wb+')时,它将显示:-IOError at/user_profileform/[Errno 21]是一个目录:'/home/ghrix/ghrixbidding/static/media'-user2644708
@csrf_exempt
def upload_file(request):
if request.method == 'POST':
print "arun";
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/user_profileform/')
else:
print "ranjeet"
form = UploadFileForm()
return render_to_response('user_profile.html', {'form': form })
def handle_uploaded_file(f):
destination = open(settings.MEDIA_ROOT, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()