Question

I have a form for uploading images.

If I follow Django's standard for cleaning a specific field attribute of a form, this is what my clean method would typically look 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 is too large ( > 15mb ).")
            return file
        else:
            raise forms.ValidationError("Could not read the uploaded file.")

However, I'm using a form that allows multiple images to be uploaded at once, all through the same widget (ie, the user can Shift+click to select several files on the file browser). So whenever I need to access the files in a view or in a handler, I use something like request.FILES.getlist('images') in a for loop. How the hell do I write a clean method for this field?? I'm lost.

Here's what my form looks like.

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

I would like the field's clean method to check the file size of each file submitted, as illustrated in the first block of code above.

Was it helpful?

Solution

Use self.files.getlist('images') in clean method to iterate over multiple 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top