0

I am using python magic to validate a file before uploading so for that I am following the below link:

https://djangosnippets.org/snippets/3039/

validators.py file:

from django.core.exceptions import ValidationError
import magic


class MimetypeValidator(object):
    def __init__(self, mimetypes):
        self.mimetypes = mimetypes

    def __call__(self, value):
        try:
            mime_byt = magic.from_buffer(value.read(1024), mime=True)
            mime = mime_byt.decode(encoding='UTF-8')
            if mime not in self.mimetypes:
                raise ValidationError('%s is not an acceptable file type' % value)
        except AttributeError as e:
            raise ValidationError('This value could not be validated for file type' % value)

here is my form.py file:

class FileForm(forms.ModelForm):
    file = forms.FileField(
        label='Select a File *',
        allow_empty_file=False,
        validators=[MimetypeValidator('application/pdf')],
        help_text='Max. Size - 25 MB')

    class Meta:
        model = File
        fields = ('file')

SO I am able to upload a pdf file with this python magic logic but I also want to allow to upload a image tiff file and restrict the file size to 25 MB.

How can I implement this by using python magic?

1 Answer 1

2

You don't need any library to do this - you can check the uploaded size of a file in the clean method on the form:

def clean_file(self):
    file = self.cleaned_data['file']
    if file.size > 25000000:
        raise ValidationError('The file is too big')
    return file
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. I also want to allow a image tiff file so do you have any idea how to add it?
Exactly the same way as you're checking for a PDF... You know how to do that bit already.
I mean I want to only allow both the pdf and tiff file while uploading the file.
Do you mean want to allow either an unlimited size PDF, or a 25MB tiff? Or do you want to allow either a PDF or tiff, both restricted to 25MB?
Yes I want to allow either a PDF or tiff, both restricted to 25MB.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.