python – 如何在不创建模型的情况下在django中保存文件
发布时间:2020-12-20 13:42:52 所属栏目:Python 来源:网络整理
导读:我想上传excel文件并将该文件保存到 django中的特定位置,而无需为该文件创建模型. 我在这里试过 我的forms.py文件 class UploadFileForm(forms.Form): file = forms.FileField(label='Select a file',help_text='max. 42 megabytes') 我的views.py import xl
我想上传excel文件并将该文件保存到
django中的特定位置,而无需为该文件创建模型.
我在这里试过 class UploadFileForm(forms.Form): file = forms.FileField(label='Select a file',help_text='max. 42 megabytes') 我的views.py import xlrd from property.forms import UploadFileForm def excel(request): if request.method == 'POST': form = UploadFileForm(request.POST,request.FILES) if form.is_valid(): newdoc = handle_uploaded_file(request.FILES['file']) print newdoc print "you in" newdoc.save() return HttpResponseRedirect(reverse('upload.views.excel')) else: form = UploadFileForm() # A empty,unbound form #documents = Document.objects.all() return render_to_response('property/list.html',{'form': form},context_instance=RequestContext(request)) def handle_uploaded_file(f): destination = open('media/file/sheet.xls','wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() 所以在尝试这个时我得到了错误. IOError at /property/excel/ [Errno 2] No such file or directory: 'media/file/sheet.xls' Request Method: POST Request URL: http://127.0.0.1:8000/property/excel/ Django Version: 1.5 Exception Type: IOError Exception Value: [Errno 2] No such file or directory: 'media/file/sheet.xls' Exception Location: D:Django_workspace6thMarchdtzpropertyviews.py in handle_uploaded_file,line 785 请帮我解决这个问题,handle_uploaded_file()函数有问题. 解决方法
如果你使用open(如open(‘path’,’wb’),那么你需要使用FULL路径.
你能做的是: from django.conf import settings destination = open(settings.MEDIA_ROOT + filename,'wb+') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |