How do I clean multiple files at once on a FileField with multiple attachments?

Viewed 35

I am looking to throw a validation error if the user tries to upload more than 1 video file (they are allowed to upload more than 1 image).

Here is the code for the field:

media = forms.FileField(
        widget=forms.ClearableFileInput(attrs={"multiple": True}),
        label="Add image/video",
        required=False,
        validators=[validate_file_size, validate_file_extension],
    )

I am able to go through each file one by one using a validator on the field (checking the file extension of each file), or by using the clean function.

1 Answers

on your form POST view

files=request.FILES.get('media')
for file in files:
    if file.content_type.__contains__('image'):
        photos += 1
    elif file.content_type.__contains__('video'):
        videos += 1
    else:
        photos=-1
        break

if videos>1:
    # throw more than one video error
if photos>5: # if you want to limit photos selection too
    # throw more than five photos error
if photos==-1:
    # throw invalid media error
Related