Login

File Mimetype Validator (Using python-magic)

Author:
BHSPitMonkey
Posted:
April 1, 2014
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

This validator works well with FileField form fields and can validate that an uploaded file has an acceptable mimetype. Place this snippet in your app's validators.py.

Requirements:

This snippet uses python-magic. To install:

pip install python-magic

Usage (in forms.py):

from validators import MimetypeValidator

class MyForm(forms.Form):
    file = forms.FileField(
        allow_empty_file=False,
        validators=[MimetypeValidator('application/pdf')],
        help_text="Upload a PDF file"
    )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.core.exceptions import ValidationError
import magic


class MimetypeValidator(object):
	def __init__(self, mimetypes):
		self.mimetypes = mimetypes
	
	def __call__(self, value):
		try:
			mime = magic.from_buffer(value.read(1024), mime=True)
			if not mime 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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.