-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontenttyperestrictedfilefield.py
43 lines (39 loc) · 1.75 KB
/
contenttyperestrictedfilefield.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#http://bixly.com/blog/accept-only-specific-file-types-in-django-file-upload/
from django.db.models import FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
class ContentTypeRestrictedFileField(FileField):
"""
Same as FileField, but you can specify:
* content_types - list containing allowed content_types.
Example: ['application/pdf', 'image/jpeg']
* max_upload_size - a number indicating the maximum file
size allowed for upload.
2.5MB - 2621440
5MB - 5242880
10MB - 10485760
20MB - 20971520
50MB - 5242880
100MB 104857600
250MB - 214958080
500MB - 429916160
"""
def __init__(self, content_types=[], max_upload_size=429916160, **kwargs):
self.content_types = content_types
self.max_upload_size = max_upload_size
super(ContentTypeRestrictedFileField, self).__init__(**kwargs)
def clean(self, *args, **kwargs):
data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)
file = data.file
try:
content_type = file.content_type
if self.content_types == [] or content_type in self.content_types:
if file.size > self.max_upload_size:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s')
% (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
else:
raise forms.ValidationError(_('Filetype %s not supported.'%content_type))
except AttributeError:
pass
return data