【问题标题】:Django: How to write a clean method for a field that allows mutiple file uploads?Django:如何为允许多个文件上传的字段编写一个干净的方法?
【发布时间】:2013-01-01 19:06:18
【问题描述】:

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

如果我遵循 Django 的 cleaning a specific field attribute of a form 标准,这就是我的 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.")

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

这是我的表单的样子。

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

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

【问题讨论】:

    标签: python django forms django-forms form-fields


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2022-09-26
      • 1970-01-01
      • 2011-05-03
      • 2013-10-08
      相关资源
      最近更新 更多