7
7
8
8
import magic
9
9
10
+
10
11
class ValidatedFileField (models .FileField ):
11
12
def __init__ (self , * args , ** kwargs ):
12
13
self .content_types = kwargs .pop ("content_types" , [])
@@ -18,16 +19,20 @@ def clean(self, *args, **kwargs):
18
19
file = data .file
19
20
20
21
if self .content_types :
21
- content_type_headers = getattr (file , 'content_type' , '' )
22
+ uploaded_content_type = getattr (file , 'content_type' , '' )
22
23
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 ())
25
26
file .seek (0 )
26
27
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 :
28
33
raise forms .ValidationError (_ ('Files of type %(type)s are not supported.' ) % {'type' : content_type_magic })
29
34
30
- if self .max_upload_size :
35
+ if self .max_upload_size and hasattr ( file , '_size' ) :
31
36
if file ._size > self .max_upload_size :
32
37
raise forms .ValidationError (_ ('Files of size greater than %(max_size)s are not allowed. Your file is %(current_size)s' ) %
33
38
{'max_size' : filesizeformat (self .max_upload_size ),
@@ -76,4 +81,4 @@ def __call__(self, file):
76
81
raise forms .ValidationError (_ ('Please keep the total uploaded files under %(total_size)s. With this file, the total would be %(exceed_size)s.' %
77
82
{'total_size' : filesizeformat (self .quota .max_usage ),
78
83
'exceed_size' : filesizeformat (self .quota .current_usage + file_size )}))
79
-
84
+
0 commit comments