Validate by file content type and size

 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. Custom FileField with content type and size validation by nemesis 2 years, 8 months ago
  2. Amazon S3 browser-based upload form(FIXED) by grillermo 8 months, 2 weeks ago
  3. Database file storage by powerfox 4 years, 4 months ago
  4. Faster pagination / model object seeking (10x faster infact :o) for larger datasets (500k +) by sleepycal 2 years, 6 months ago
  5. FileField with file extension whitelist by jedie 4 years, 10 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
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!

#

(Forgotten your password?)