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?

Sneha Shinde
  • 343
  • 7
  • 18

1 Answers1

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
Ben
  • 6,687
  • 2
  • 33
  • 46
  • Thanks. I also want to allow a image tiff file so do you have any idea how to add it? – Sneha Shinde May 26 '16 at 11:09
  • Exactly the same way as you're checking for a PDF... You know how to do that bit already. – Ben May 26 '16 at 15:52
  • I mean I want to only allow both the pdf and tiff file while uploading the file. – Sneha Shinde May 26 '16 at 19:31
  • 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? – Ben May 27 '16 at 05:59
  • Yes I want to allow either a PDF or tiff, both restricted to 25MB. – Sneha Shinde May 27 '16 at 07:10
  • Then just change the validator in your original question to `MimetypeValidator(['application/pdf', 'image/tiff'])]`. Where did you get that code from in your original post? It won't work as is (needs to take a list not a string). – Ben May 27 '16 at 07:25
  • I have mentioned the link above: https://djangosnippets.org/snippets/3039/....when I use MimetypeValidator(['application/pdf', 'image/tiff'])],I ma getti g an error : TypeError: can only concatenate list (not "MimetypeValidator") to list – Sneha Shinde May 27 '16 at 08:39
  • What line is giving you that error? Does your full line now read: `validators=[MimetypeValidator(['application/pdf', 'image/tiff'])],` ? – Ben May 27 '16 at 09:09