Skip to content

Commit 2edcdb5

Browse files
committed
Update MongoFileInput widget with full input nesting + Add MongoImageInput widget
1 parent 2291129 commit 2edcdb5

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

flask_mongoengine/wtf/widgets.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""Custom widgets for Mongo fields."""
22
from markupsafe import Markup, escape
3-
from mongoengine.fields import GridFSProxy
4-
from wtforms.widgets import html_params
3+
from mongoengine.fields import GridFSProxy, ImageGridFsProxy
4+
from wtforms.widgets.core import FileInput
55

66

7-
class MongoFileInput(object):
7+
class MongoFileInput(FileInput):
88
"""Renders a file input field with delete option."""
99

1010
template = """
@@ -14,21 +14,27 @@ class MongoFileInput(object):
1414
</div>
1515
"""
1616

17-
def __call__(self, field, **kwargs):
18-
kwargs.setdefault("id", field.id)
17+
def _is_supported_file(self, field) -> bool:
18+
"""Checks type of file input."""
19+
return field.data and isinstance(field.data, GridFSProxy)
20+
21+
def __call__(self, field, **kwargs) -> Markup:
1922
placeholder = ""
20-
if field.data and isinstance(field.data, GridFSProxy):
21-
data = field.data
23+
24+
if self._is_supported_file(field):
2225
placeholder = self.template % {
23-
"name": escape(data.name),
24-
"content_type": escape(data.content_type),
25-
"size": data.length // 1024,
26+
"name": escape(field.data.name),
27+
"content_type": escape(field.data.content_type),
28+
"size": field.data.length // 1024,
2629
"marker": f"_{field.name}_delete",
2730
}
2831

29-
return Markup(
30-
(
31-
"%s<input %s>"
32-
% (placeholder, html_params(name=field.name, type="file", **kwargs))
33-
)
34-
)
32+
return Markup(placeholder) + super().__call__(field, **kwargs)
33+
34+
35+
class MongoImageInput(MongoFileInput):
36+
"""Renders an image input field with delete option."""
37+
38+
def _is_supported_file(self, field) -> bool:
39+
"""Checks type of file input."""
40+
return field.data and isinstance(field.data, ImageGridFsProxy)

0 commit comments

Comments
 (0)