File tree Expand file tree Collapse file tree 5 files changed +47
-6
lines changed Expand file tree Collapse file tree 5 files changed +47
-6
lines changed Original file line number Diff line number Diff line change 1
1
import os
2
2
3
+ PROJECT_ROOT = os .path .dirname (os .path .realpath (__file__ ))
4
+
3
5
DEBUG = True
4
6
5
7
AUTHNET_LOGIN_ID = ''
48
50
49
51
USE_I18N = True
50
52
53
+ MEDIA_ROOT = os .path .join (PROJECT_ROOT , 'media' )
54
+
55
+ MEDIA_URL = '/media/'
56
+
Original file line number Diff line number Diff line change 1
- from django .db import models
1
+ from django .db . models import FileField
2
2
3
- class ValidatedFileField (models .FileField ):
4
- pass
3
+ class ValidatedFileField (FileField ):
4
+ def __init__ (self , * args , ** kwargs ):
5
+ self .content_types = kwargs .pop ("content_types" )
6
+ self .max_upload_size = kwargs .pop ("max_upload_size" )
7
+ super (ValidatedFileField , self ).__init__ (* args , ** kwargs )
5
8
9
+ def clean (self , * args , ** kwargs ):
10
+ data = super (ValidatedFileField , self ).clean (* args , ** kwargs )
11
+
12
+ file = data .file
13
+ try :
14
+ content_type = file .content_type
15
+ if content_type in self .content_types :
16
+ if file ._size > self .max_upload_size :
17
+ raise forms .ValidationError (_ ('Please keep filesize under %s. Current filesize %s' ) % (filesizeformat (self .max_upload_size ), filesizeformat (file ._size )))
18
+ else :
19
+ raise forms .ValidationError (_ ('Filetype not supported.' ))
20
+ except AttributeError :
21
+ pass
22
+
23
+ return data
Original file line number Diff line number Diff line change 1
1
from django .test import TestCase
2
+ from django .core .files import File
2
3
3
4
from models import TestModel
4
5
5
6
class ValidatedFileFieldTest (TestCase ):
6
7
7
- def test_create_instance (self ):
8
- instance = TestModel ()
8
+ def test_create_empty_instance (self ):
9
+ instance = TestModel . objects . create ()
9
10
instance .save ()
10
11
12
+ def test_create_instance_with_file (self ):
13
+ instance = TestModel .objects .create (
14
+ the_file = File (open ('validatedfile/tests/image2k.png' ), 'the_file.png' )
15
+ )
16
+ instance .save ()
17
+
18
+ self .assertEqual (instance .the_file .url , '/media/testfile/the_file.png' )
19
+
20
+ instance .the_file .delete ()
21
+ instance .delete ()
22
+
Original file line number Diff line number Diff line change 3
3
from ..models import *
4
4
5
5
class TestModel (models .Model ):
6
- the_file = ValidatedFileField (upload_to = 'testfile' )
6
+ the_file = ValidatedFileField (
7
+ null = True ,
8
+ blank = True ,
9
+ upload_to = 'testfile' ,
10
+ content_types = 'image/png' ,
11
+ max_upload_size = 10240 )
7
12
You can’t perform that action at this time.
0 commit comments