1

アップロードしたファイルを 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+
4

1 に答える 1

0

モデルSpreadsheetに がある場合FileField、ファイルをディスクに保存するために必要なことは、フォームに渡しrequest.FILESてフォームを保存することだけです。

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)
于 2013-07-29T11:55:56.640 に答える