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?