Skip to content

Commit d37e892

Browse files
author
Jan Schrewe
committed
Correctly init proxy_class for new images
1 parent da4b134 commit d37e892

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

mongodbforms/documents.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,18 @@ def _get_unique_filename(name):
3939
# The awesome Mongoengine ImageGridFsProxy wants to pull a field
4040
# from a document to get necessary data. Trouble is that this doesn't work
4141
# if the ImageField is stored on List or MapField. So we pass a nice fake
42-
# document to
42+
# document to the proxy to get saving the file done. Yeah it really is that ugly.
4343
class FakeDocument(object):
44+
_fields = {}
45+
4446
def __init__(self, key, field):
4547
super(FakeDocument, self).__init__()
46-
if not hasattr(self, '_fields'):
47-
self._fields = {}
48-
self._fields.update({key: field})
49-
48+
49+
self._fields[key] = field
50+
51+
# don't care if anything gets marked on this
52+
# we do update a real field later though. That should
53+
# trigger the same thing on the real document though.
5054
def _mark_as_changed(self, key):
5155
pass
5256

@@ -90,30 +94,36 @@ def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
9094
file_data = map_field.get(key, None)
9195
uploaded_file.seek(0)
9296
filename = _get_unique_filename(uploaded_file.name)
93-
# add a file
94-
_fake_document = FakeDocument(f.name, f.field)
97+
fake_document = FakeDocument(f.name, f.field)
9598
overwrote_instance = False
9699
overwrote_key = False
100+
# save a new file
97101
if file_data is None:
98-
proxy = f.field.proxy_class(instance=_fake_document, key=f.name)
102+
proxy = f.field.proxy_class(instance=fake_document, key=f.name,
103+
db_alias=f.field.db_alias,
104+
collection_name=f.field.collection_name)
99105
proxy.put(uploaded_file, content_type=uploaded_file.content_type, filename=filename)
106+
proxy.close()
100107
proxy.instance = None
101108
proxy.key = None
102109
map_field[key] = proxy
110+
# overwrite an existing file
103111
else:
104112
if file_data.instance is None:
113+
file_data.instance = fake_document
105114
overwrote_instance = True
106-
file_data.instance = _fake_document
107115
if file_data.key is None:
108116
file_data.key = f.name
109117
overwrote_key = True
110118
file_data.delete()
111119
file_data.put(uploaded_file, content_type=uploaded_file.content_type, filename=filename)
120+
file_data.close()
112121
if overwrote_instance:
113122
file_data.instance = None
114123
if overwrote_key:
115124
file_data.key = None
116125
map_field[key] = file_data
126+
print map_field
117127
setattr(instance, f.name, map_field)
118128
else:
119129
field = getattr(instance, f.name)

0 commit comments

Comments
 (0)