python - Django: How to write a clean method for a field that allows mutiple file uploads? -
i have form uploading images.
if follow django's standard cleaning specific field attribute of form, clean method typically like:
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 large ( > 15mb ).") return file else: raise forms.validationerror("could not read uploaded file.")
however, i'm using form allows multiple images uploaded @ once, through same widget (ie, user can shift+click select several files on file browser). whenever need access files in view or in handler, use request.files.getlist('images')
in loop. how hell write clean method field?? i'm lost.
here's form looks like.
class uploadimagesform(forms.form): images = forms.filefield(widget=forms.clearablefileinput(attrs={'multiple': 'multiple'}))
i field's clean method check file size of each file submitted, illustrated in first block of code above.
use self.files.getlist('images')
in clean
method iterate on multiple images:
def clean_images(self): files = self.files.getlist('images') file in files: if file: if file._size > 15*1024*1024: raise forms.validationerror("image file large ( > 15mb ).") else: raise forms.validationerror("could not read uploaded file.") return files
Comments
Post a Comment