django上传文件证明比必要更困难

时间:2016-02-12 17:54:01

标签: python django file-handling

我正在尝试允许用户在我的django网站上传文件。我从django文档中的示例命令开始,输入到views.py,独立于表单或模型,并在模板中引用(并对其进行修改以便可以一次上载多个文件):

  def Upload(request):
    for count, x in enumerate(request.FILES.getlist("files")):# allows for multiple iterations/files
      def process():
         with open('/Users/Deirdre/bing/upload/media/file_', + str(count) 'wb+') as destination:
            for chunk in f.chunks():
               destination.write(chunk)
       process(x)
     return HttpResponse("File(s) uploaded")

然而,在“with open ... as”中,服务器不断返回错误“SyntaxError:invalid syntax”或“unexpected indentation”.... 我知道这些都不是真的,有没有办法绕过这个困难?为什么django没有配置命令???

1 个答案:

答案 0 :(得分:-1)

你的缩进是错误的!下面给出了正确的缩进,必须有4个空格缩进

from django.shortcuts import render
from django.http import HttpResponse

def Upload(request):
    for count, x in enumerate(request.FILES.getlist("files")):
        def process(f):
            with open('/Users/Michel/django_1.8/projects/upload/media/file_' + str(count), 'wb+') as destination:
                for chunk in f.chunks():
                    destination.write(chunk)
        process(x)
    return HttpResponse("File(s) uploaded!")