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

标签 python django forms django-forms form-fields

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

如果我遵循 Django 的 cleaning a specific field attribute of a form 标准,这就是我的清理方法通常的样子:

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 键并单击以在文件浏览器中选择多个文件)。因此,每当我需要在 View 或处理程序中访问文件时,我都会在 for 循环中使用类似 request.FILES.getlist('images') 的东西。我到底该如何为这个领域写一个干净的方法?我迷路了。

这是我的表单的样子。

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

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

最佳答案

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

关于python - Django:如何为允许多个文件上传的字段编写一个干净的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392700/

相关文章:

python - python 模块(igraph)安装接近结束时出现权限被拒绝错误

python - 如何按列值的计数进行分组并对其进行排序?

python - 无法使用 athena 数据库连接到超集

python - 使用两个模型进行全文搜索

python - 动态添加表单字段到django表单

javascript - 通过在 jQuery 中单击将 INPUT FILE 值复制到 INPUT TEXT

python - "Merge"替换 Keras/Tensorflow/Python3

django - 使用来自 JSON 的数据使用 DRF Serializer 更新对象

python - Django 项目的 Pyinstaller 错误 "ImportError: No module named ' django.contrib.admin.apps'”

php - Symfony 表单错误 - 名称为空的表单不能有父表单