Skip to content

Commit 32c13ca

Browse files
committed
Improve the type detection and better support for django admin
1 parent 38fc97d commit 32c13ca

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

validatedfile/__init__.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
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", [])
@@ -18,16 +19,20 @@ def clean(self, *args, **kwargs):
1819
file = data.file
1920

2021
if self.content_types:
21-
content_type_headers = getattr(file, 'content_type', '')
22+
uploaded_content_type = getattr(file, 'content_type', '')
2223

23-
mg = magic.Magic(mime = True)
24-
content_type_magic = mg.from_buffer(file.read(1024))
24+
mg = magic.Magic(mime=True)
25+
content_type_magic = mg.from_buffer(file.read())
2526
file.seek(0)
2627

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

30-
if self.max_upload_size:
35+
if self.max_upload_size and hasattr(file, '_size'):
3136
if file._size > self.max_upload_size:
3237
raise forms.ValidationError(_('Files of size greater than %(max_size)s are not allowed. Your file is %(current_size)s') %
3338
{'max_size': filesizeformat(self.max_upload_size),
@@ -76,4 +81,4 @@ def __call__(self, file):
7681
raise forms.ValidationError(_('Please keep the total uploaded files under %(total_size)s. With this file, the total would be %(exceed_size)s.' %
7782
{'total_size': filesizeformat(self.quota.max_usage),
7883
'exceed_size': filesizeformat(self.quota.current_usage + file_size)}))
79-
84+

0 commit comments

Comments
 (0)