1
+ import os
2
+ import itertools
3
+
1
4
from django .utils .datastructures import SortedDict
2
5
3
6
from django .forms .forms import BaseForm , get_declared_fields , NON_FIELD_ERRORS , pretty_name
11
14
from django .forms .widgets import HiddenInput
12
15
13
16
from util import MongoFormFieldGenerator
14
- from mongoengine .fields import ObjectIdField , ListField , ReferenceField
17
+ from mongoengine .fields import ObjectIdField , ListField
15
18
from mongoengine .base import ValidationError
19
+ from mongoengine .connection import _get_db
16
20
17
21
from documentoptions import AdminOptions
18
- from util import init_document_options
19
22
23
+ import gridfs
24
+
25
+ def _get_unique_filename (name ):
26
+ fs = gridfs .GridFS (_get_db ())
27
+ file_root , file_ext = os .path .splitext (name )
28
+ count = itertools .count (1 )
29
+ while fs .exists (filename = name ):
30
+ # file_ext includes the dot.
31
+ name = os .path .join ("%s_%s%s" % (file_root , count .next (), file_ext ))
32
+ return name
20
33
21
34
def construct_instance (form , instance , fields = None , exclude = None , ignore = None ):
22
35
"""
@@ -27,8 +40,8 @@ def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
27
40
from mongoengine .fields import FileField
28
41
cleaned_data = form .cleaned_data
29
42
file_field_list = []
43
+
30
44
# check wether object is instantiated
31
- # TODO: IS there a better way to do this?
32
45
if isinstance (instance , type ):
33
46
instance = instance ()
34
47
@@ -49,7 +62,13 @@ def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
49
62
setattr (instance , f .name , cleaned_data [f .name ])
50
63
51
64
for f in file_field_list :
52
- f .save_form_data (instance , cleaned_data [f .name ])
65
+ upload = cleaned_data [f .name ]
66
+ field = getattr (instance , f .name )
67
+ filename = _get_unique_filename (upload .name )
68
+ upload .file .seek (0 )
69
+ field .replace (upload , content_type = upload .content_type , filename = filename )
70
+ field .filename = 'blah blup'
71
+ setattr (instance , f .name , field )
53
72
54
73
return instance
55
74
0 commit comments