我有一个用于上传图像的表单。
如果我遵循 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.")
但是,我使用的表单允许通过同一个小部件一次上传多个图像(即,用户可以按住 Shift 键并单击以在文件浏览器上选择多个文件)。因此,每当我需要访问视图或处理程序中的文件时,我都会使用类似的东西request.FILES.getlist('images')
在 for 循环中。我到底该如何为这个领域编写一个干净的方法?我迷路了。
这是我的表格的样子。
class UploadImagesForm(forms.Form):
images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': 'multiple'}))
我想要该字段的 clean 方法来检查文件大小每个提交的文件,如上面第一段代码所示。
Use self.files.getlist('images')
in 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)