Django: How to write a clean method for a field that allows mutiple file uploads?

浪尽此生 提交于 2019-12-08 01:11:00

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/14392700/django-how-to-write-a-clean-method-for-a-field-that-allows-mutiple-file-uploads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!