3

我有一个上传图片的表格。

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

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.")

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

这是我的表格的样子。

class UploadImagesForm(forms.Form):
    images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': 'multiple'}))

我希望该字段的 clean 方法来检查每个提交的文件的文件大小,如上面的第一个代码块所示。

4

1 回答 1

10

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

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
于 2013-01-18T05:42:59.010 回答