1
1
"""Custom widgets for Mongo fields."""
2
2
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
5
5
6
6
7
- class MongoFileInput (object ):
7
+ class MongoFileInput (FileInput ):
8
8
"""Renders a file input field with delete option."""
9
9
10
10
template = """
@@ -14,21 +14,27 @@ class MongoFileInput(object):
14
14
</div>
15
15
"""
16
16
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 :
19
22
placeholder = ""
20
- if field . data and isinstance ( field . data , GridFSProxy ):
21
- data = field . data
23
+
24
+ if self . _is_supported_file ( field ):
22
25
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 ,
26
29
"marker" : f"_{ field .name } _delete" ,
27
30
}
28
31
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