Django:如何为允许多个文件上传的字段编写一个干净的方法?

sga*_*a62 2 python forms django django-forms form-fields

我有一张上传图片的表格.

如果我遵循Django的标准来清理表单的特定字段属性,那么这就是我的clean方法通常的样子:

class UploadImagesForm(forms.Form):
    image = forms.FileField()

    def clean_image(self):
        file = self.cleaned_data['image']
        if file:
            if file._size > 15*1024*1024:
                raise forms.ValidationError("Image file is too large ( > 15mb ).")
            return file
        else:
            raise forms.ValidationError("Could not read the uploaded file.")
Run Code Online (Sandbox Code Playgroud)

但是,我正在使用一个允许一次上传多个图像的表单,所有这些都通过相同的小部件(即,用户可以按住Shift并单击以选择文件浏览器上的多个文件).因此,每当我需要访问视图或处理程序中的文件时,我都会使用类似于request.FILES.getlist('images')for循环的东西.我该怎么办这个领域的干净方法?我迷路了.

这是我的表格的样子.

class UploadImagesForm(forms.Form):
    images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': 'multiple'}))
Run Code Online (Sandbox Code Playgroud)

我想要字段的干净方法来检查提交每个文件的文件大小,如上面第一段代码所示.

Aam*_*nan 8

self.files.getlist('images')clean方法中使用迭代多个图像:

def clean_images(self):
    files = self.files.getlist('images')
    for file in files:
        if file:
            if file._size > 15*1024*1024:
                raise forms.ValidationError("Image file is too large ( > 15mb ).")
        else:
            raise forms.ValidationError("Could not read the uploaded file.")
    return files
Run Code Online (Sandbox Code Playgroud)