Skip to content

Commit cad6375

Browse files
author
Jan Schrewe
committed
Totally does FileFields now. Getting them to the client is still your job.
1 parent dec4418 commit cad6375

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

mongodbforms/documents.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import os
2+
import itertools
3+
14
from django.utils.datastructures import SortedDict
25

36
from django.forms.forms import BaseForm, get_declared_fields, NON_FIELD_ERRORS, pretty_name
@@ -11,12 +14,22 @@
1114
from django.forms.widgets import HiddenInput
1215

1316
from util import MongoFormFieldGenerator
14-
from mongoengine.fields import ObjectIdField, ListField, ReferenceField
17+
from mongoengine.fields import ObjectIdField, ListField
1518
from mongoengine.base import ValidationError
19+
from mongoengine.connection import _get_db
1620

1721
from documentoptions import AdminOptions
18-
from util import init_document_options
1922

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
2033

2134
def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
2235
"""
@@ -27,8 +40,8 @@ def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
2740
from mongoengine.fields import FileField
2841
cleaned_data = form.cleaned_data
2942
file_field_list = []
43+
3044
# check wether object is instantiated
31-
# TODO: IS there a better way to do this?
3245
if isinstance(instance, type):
3346
instance = instance()
3447

@@ -49,7 +62,13 @@ def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
4962
setattr(instance, f.name, cleaned_data[f.name])
5063

5164
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)
5372

5473
return instance
5574

0 commit comments

Comments
 (0)