Login

File Mimetype Validator (Using python-magic)

Author:
BHSPitMonkey
Posted:
April 1, 2014
Language:
Python
Version:
Not specified
Tags:
validation upload magic mimetype FileField
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. A form field for valdating PDF and Microsoft Word document by jimmylam 6 years, 9 months ago
  2. Custom FileField with content type and size validation by nemesis 4 years, 11 months ago
  3. pyText2Pdf - Python script to convert plain text into PDF file. Modified to work with streams. by vsergeyev 5 years, 9 months ago
  4. Easy file upload handler by mattdw 6 years, 11 months ago
  5. Validate by file content type and size by macmichael01 6 years, 6 months ago

Comments

Please login first before commenting.