如何在django中保存文件而不创建模型

如何在django中保存文件而不创建模型

本文介绍了如何在django中保存文件而不创建模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传excel文件,并将该文件保存到django中的特定位置,而不创建该文件的模型。

I want to upload excel file and save that file to specific location in django without creating model for that file.

我在这里尝试过
我的表单。 py文件

I tried heremy forms.py file

class UploadFileForm(forms.Form):

    file  = forms.FileField(label='Select a file',
        help_text='max. 42 megabytes')

我的意见.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()

所以在尝试这个时候我收到错误。 >

So while trying this i am getting the error.

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_workspace\6thMarch\dtz\property\views.py in handle_uploaded_file, line 785

请帮我解决这个问题,在handle_uploaded_file()函数中有一个问题。

Please help me out for this, There is a problem in handle_uploaded_file() function.

推荐答案

如果你使用open(如open('path','wb + '),那么你需要使用FULL路径。

If you use open (as in open('path', 'wb+'), then you need to use FULL path.

你可以做的是:

from django.conf import settings
destination = open(settings.MEDIA_ROOT + filename, 'wb+')

这篇关于如何在django中保存文件而不创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 05:31