Django Filefield Image and Video Restriction

Asked

Viewed 186 times

-1

I would like to know how I can limit the file type on FileField django?

I know I can add this validation in the Form. I just wish you could send videos and images in this field, nothing else.

1 answer

0

I found a way to identify the mime type of the file. Follow the example of the form where I limit the image and video and do not allow . bmp files:

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = ("file", "name", "email", "subject", "message",)

    def clean( self ): 
        cleaned_data = self.cleaned_data
        file = cleaned_data.get( "file", None )
        if file:
            if file.content_type.split('/')[0] not in ['image', 'video']:
                raise forms.ValidationError( 'Enviar apenas video ou imagem.' )
            if file.content_type == 'image/bmp':
                raise forms.ValidationError( 'Arquivos .BMP não permitidos.' )
        return cleaned_data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.