Django: Uploading multiple files. List of files needed in cleaned_data['file']

前端 未结 3 1861
北恋
北恋 2020-12-20 13:12

I followed the pattern of the docs, to upload several files with one forms.FileField:

https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#u

3条回答
  •  误落风尘
    2020-12-20 14:11

    I assume that you have:

    class FileFieldForm(forms.Form):
         files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    

    and you are trying to get files using : cleaned_data['files'] and you are getting only 1 file instead of 2.

    The Reason:

    What is happening here is, When you try to do something like this

    file in self.cleaned_data['files]:, 
    

    thinking that, you can iterate over a list of uploadedFile objects and pass each to the handler function.

    But cleaned_data['files'] is not a list for you, it's just ONE single instance of uploadedfile.

    When you iterate over a file object, you're actually reading it. So what you pass eventually to the handler function is not the file object but its content (as a bytes string).

    The solution

    You need to get a list of files and then, perform something what you want on them as below.

    files = request.FILES.getlist('files')
    
    for f in files:
        ...  # Do something with each file considering f as file object
    

提交回复
热议问题