Skip to content

Commit 93fbf49

Browse files
committed
Merge pull request #1 from jarus/improve_type_detection
Improve the type detection and better support for django admin
2 parents 38fc97d + 4ffeac1 commit 93fbf49

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

validatedfile/__init__.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,35 @@
77

88
import magic
99

10+
1011
class ValidatedFileField(models.FileField):
1112
def __init__(self, *args, **kwargs):
1213
self.content_types = kwargs.pop("content_types", [])
1314
self.max_upload_size = kwargs.pop("max_upload_size", 0)
15+
self.mime_lookup_length = kwargs.pop("mime_lookup_length", 4096)
1416
super(ValidatedFileField, self).__init__(*args, **kwargs)
1517

1618
def clean(self, *args, **kwargs):
1719
data = super(ValidatedFileField, self).clean(*args, **kwargs)
1820
file = data.file
1921

2022
if self.content_types:
21-
content_type_headers = getattr(file, 'content_type', '')
23+
uploaded_content_type = getattr(file, 'content_type', '')
2224

23-
mg = magic.Magic(mime = True)
24-
content_type_magic = mg.from_buffer(file.read(1024))
25+
mg = magic.Magic(mime=True)
26+
content_type_magic = mg.from_buffer(
27+
file.read(self.mime_lookup_length)
28+
)
2529
file.seek(0)
2630

27-
if not content_type_headers in self.content_types or not content_type_magic in self.content_types:
31+
# Prefere mime-type instead mime-type from http header
32+
if uploaded_content_type != content_type_magic:
33+
uploaded_content_type = content_type_magic
34+
35+
if not uploaded_content_type in self.content_types:
2836
raise forms.ValidationError(_('Files of type %(type)s are not supported.') % {'type': content_type_magic})
2937

30-
if self.max_upload_size:
38+
if self.max_upload_size and hasattr(file, '_size'):
3139
if file._size > self.max_upload_size:
3240
raise forms.ValidationError(_('Files of size greater than %(max_size)s are not allowed. Your file is %(current_size)s') %
3341
{'max_size': filesizeformat(self.max_upload_size),
@@ -76,4 +84,4 @@ def __call__(self, file):
7684
raise forms.ValidationError(_('Please keep the total uploaded files under %(total_size)s. With this file, the total would be %(exceed_size)s.' %
7785
{'total_size': filesizeformat(self.quota.max_usage),
7886
'exceed_size': filesizeformat(self.quota.current_usage + file_size)}))
79-
87+

0 commit comments

Comments
 (0)