如何在Django中将上传的文件保存到磁盘? - 无效模式:wb +

时间:2013-07-29 10:46:49

标签: python django

我想知道如何通过django将上传的文件保存到磁盘。

这是代码

# ...
def spreadsheet_form(request, id = None):
    if is_admin_user(request):
        instance = get_object_or_404(Spreadsheet, id=id) if id is not None else None
        form = SpreadsheetForm(request.POST or None, request.FILES or None, instance=instance)
        if form.is_valid():
            spreadsheet = form.save(commit=False)
            spreadsheet.name = request.POST['name']
            spreadsheet.spreadsheet_file = request.FILES['spreadsheet_file']
            handle_uploaded_file(request.FILES['spreadsheet_file'])
            spreadsheet.save()
            return redirect('/spreadsheets/')
        return render_to_response("pages/spreadsheet_form.html", {"form": form,"id":id},context_instance=RequestContext(request))
    else:
        return redirect('/', False)

# ...
def handle_uploaded_file(f):
    with open('/tmp/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

目前它返回以下错误:

invalid mode: wb+

Request Method:     POST
Request URL:    http://0.0.0.0:8000/spreadsheet/new/
Django Version:     1.4.5
Exception Type:     IOError
Exception Value:    

invalid mode: wb+

1 个答案:

答案 0 :(得分:0)

如果您的模型SpreadsheetFileField,那么将文件保存到磁盘只需要将request.FILES传递给表单并保存表单:< / p>

class Spreadsheet(models.Model):
    file = models.FileField(upload_to="directory/relative/to/MEDIA_ROOT/")
    other_field = ...
    etc.

class SpreadsheetForm(forms.ModelForm):
    class Meta:
        model = Spreadsheet
        fields = ['file', 'other_field', 'etc.']

def spreadsheet_form(request, id=None);
    if is_admin_user(request):
        instance = get_object_or_404(Spreadsheet, id=id) if id is not None else None
        form = SpreadsheetForm(request.POST or None, request.FILES or None, instance=instance)
        if form.is_valid():
            spreadsheet = form.save()
        return redirect('/spreadsheets/')
    return render_to_response("pages/spreadsheet_form.html", {"form": form,"id":id},context_instance=RequestContext(request))
else:
    return redirect('/', False)