我有一张上传图片的表单。
如果我遵循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并单击以选择文件浏览器上的多个文件)。因此,每当我需要访问视图或处理程序中的文件时,我在for循环中使用类似request.FILES.getlist('images')
的内容。我该怎么办这个领域的干净方法?我输了。
这是我的表格的样子。
class UploadImagesForm(forms.Form):
images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': 'multiple'}))
我希望字段的干净方法检查每个提交文件的文件大小,如上面第一段代码所示。
答案 0 :(得分: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