Last active
June 2, 2020 17:55
-
-
Save bool-dev/9e2d8440e4d50ace4ec4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Sample DecimalField. | |
""" | |
from wtforms import DecimalField | |
class BetterDecimalField(DecimalField): | |
""" | |
Very similar to WTForms DecimalField, except with the option of rounding | |
the data always. | |
""" | |
def __init__(self, label=None, validators=None, places=2, rounding=None, | |
round_always=False, **kwargs): | |
super(BetterDecimalField, self).__init__( | |
label=label, validators=validators, places=places, rounding= | |
rounding, **kwargs) | |
self.round_always = round_always | |
def process_formdata(self, valuelist): | |
if valuelist: | |
try: | |
self.data = decimal.Decimal(valuelist[0]) | |
if self.round_always and hasattr(self.data, 'quantize'): | |
exp = decimal.Decimal('.1') ** self.places | |
if self.rounding is None: | |
quantized = self.data.quantize(exp) | |
else: | |
quantized = self.data.quantize(exp, rounding= | |
self.rounding) | |
self.data = quantized | |
except (decimal.InvalidOperation, ValueError): | |
self.data = None | |
raise ValueError(self.gettext('Not a valid decimal value')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment