Skip to content

Commit 76b101e

Browse files
committed
Add special WTForms fields with None value support
1 parent 131b3d8 commit 76b101e

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

flask_mongoengine/wtf/fields.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,88 @@ def process_formdata(self, valuelist):
268268
"""
269269
if valuelist:
270270
self.data = bytes(valuelist[0], "utf-8")
271+
272+
273+
# noinspection PyUnresolvedReferences,PyAttributeOutsideInit
274+
class EmptyStringIsNoneMixin:
275+
"""
276+
Special mixin to ignore empty strings **before** parent class processing.
277+
278+
Unlike old :class:`NoneStringField` we do it before parent class call, this allows
279+
us to reuse this mixin in many more cases without errors.
280+
"""
281+
282+
def process_formdata(self, valuelist):
283+
"""
284+
Ignores empty string and calls parent :func:`process_formdata` if data present.
285+
286+
:param valuelist: A list of strings to process.
287+
"""
288+
if valuelist and valuelist[0] == "":
289+
self.data = None
290+
else:
291+
super().process_formdata(valuelist)
292+
293+
294+
class MongoEmailField(EmptyStringIsNoneMixin, wtf_fields.EmailField):
295+
"""
296+
Regular :class:`wtforms.fields.EmailField`, that transform empty string to `None`.
297+
"""
298+
299+
pass
300+
301+
302+
class MongoHiddenField(EmptyStringIsNoneMixin, wtf_fields.HiddenField):
303+
"""
304+
Regular :class:`wtforms.fields.HiddenField`, that transform empty string to `None`.
305+
"""
306+
307+
pass
308+
309+
310+
class MongoPasswordField(EmptyStringIsNoneMixin, wtf_fields.PasswordField):
311+
"""
312+
Regular :class:`wtforms.fields.PasswordField`, that transform empty string to `None`.
313+
"""
314+
315+
pass
316+
317+
318+
class MongoSearchField(EmptyStringIsNoneMixin, wtf_fields.SearchField):
319+
"""
320+
Regular :class:`wtforms.fields.SearchField`, that transform empty string to `None`.
321+
"""
322+
323+
pass
324+
325+
326+
class MongoStringField(EmptyStringIsNoneMixin, wtf_fields.StringField):
327+
"""
328+
Regular :class:`wtforms.fields.StringField`, that transform empty string to `None`.
329+
"""
330+
331+
pass
332+
333+
334+
class MongoTelField(EmptyStringIsNoneMixin, wtf_fields.TelField):
335+
"""
336+
Regular :class:`wtforms.fields.TelField`, that transform empty string to `None`.
337+
"""
338+
339+
pass
340+
341+
342+
class MongoTextAreaField(EmptyStringIsNoneMixin, wtf_fields.TextAreaField):
343+
"""
344+
Regular :class:`wtforms.fields.TextAreaField`, that transform empty string to `None`.
345+
"""
346+
347+
pass
348+
349+
350+
class MongoURLField(EmptyStringIsNoneMixin, wtf_fields.URLField):
351+
"""
352+
Regular :class:`wtforms.fields.URLField`, that transform empty string to `None`.
353+
"""
354+
355+
pass

0 commit comments

Comments
 (0)