我有一个用于上传图片的表单。
如果我遵循 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/