Login

Validate by file content type and size

Author:
macmichael01
Posted:
January 31, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

A simple way to handle file validation by checking for a proper content_type and by making sure that the file does not go over its limit upload size limit.

In the example I am checking to make sure the file is an image or a video file then I check to make sure that the file is below the max upload limit. if conditions are not met, then a validation error is raised

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Add to your settings file
CONTENT_TYPES = ['image', 'video']
# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB 104857600
# 250MB - 214958080
# 500MB - 429916160
MAX_UPLOAD_SIZE = "5242880"

#Add to a form containing a FileField and change the field names accordingly.
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
def clean_content(self):
    content = self.cleaned_data['content']
    content_type = content.content_type.split('/')[0]
    if content_type in settings.CONTENT_TYPES:
        if content._size > settings.MAX_UPLOAD_SIZE:
            raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
    else:
        raise forms.ValidationError(_('File type is not supported'))
    return content

More like this

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

Comments

andynguyen (on February 11, 2009):

Thanks for this snippet. One thing you might want to change is the quotes around MAX_UPLOAD_SIZE. I struggled with the validation not throwing an error because it was seeing MAX_UPLOAD_SIZE as a string.

#

chrisdev (on November 17, 2011):

If you simply submit the form for an instance which already contains an uploaded file/image this method will fail with an attribute exception since "content" only has a content_type attribute when a file is being uploaded else content will just be a file object with no content type.

you need something like<br /> if hasattr(content,"content_type"):

#

chizeng (on December 26, 2011):

How would one extend this to limiting pdf and word documents? Would one simply add 'application/msword' and 'application/pdf' to the CONTENT_TYPES dictionary in settings?

It's not working for me. Thanks!

#

arunkreddy (on March 21, 2014):

#19 content_type = content.content_type.split('/')[0]

change it to:

#19 content_type = content.content_type.split('/')[1]

now you can add:

CONTENT_TYPES = ['pdf','doc']

#

Please login first before commenting.