From ab23a8067c34c10d764c67b45f08347e9550176f Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Mon, 20 Jul 2015 12:47:37 -0500 Subject: [PATCH] Add `DecimalFieldRenderer`. --- tailbone/forms/renderers/__init__.py | 1 + tailbone/forms/renderers/common.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/tailbone/forms/renderers/__init__.py b/tailbone/forms/renderers/__init__.py index 77645e73..084933dc 100644 --- a/tailbone/forms/renderers/__init__.py +++ b/tailbone/forms/renderers/__init__.py @@ -27,6 +27,7 @@ FormAlchemy Field Renderers from tailbone.forms.renderers.common import ( AutocompleteFieldRenderer, DateTimeFieldRenderer, + DecimalFieldRenderer, EnumFieldRenderer, YesNoFieldRenderer, ) diff --git a/tailbone/forms/renderers/common.py b/tailbone/forms/renderers/common.py index bf34d9c4..1638ece1 100644 --- a/tailbone/forms/renderers/common.py +++ b/tailbone/forms/renderers/common.py @@ -124,6 +124,29 @@ class EnumFieldRenderer(SelectFieldRenderer): return SelectFieldRenderer.render(self, opts, **kwargs) +class DecimalFieldRenderer(formalchemy.FieldRenderer): + """ + Sort of generic field renderer for decimal values. You must provide the + number of places after the decimal (scale). Note that this in turn relies + on simple string formatting; the renderer does not attempt any mathematics + of its own. + """ + + def __init__(self, scale): + self.scale = scale + + def __call__(self, field): + super(DecimalFieldRenderer, self).__init__(field) + return self + + def render_readonly(self, **kwargs): + value = self.raw_value + if value is None: + return '' + fmt = '{{0:0.{0}f}}'.format(self.scale) + return fmt.format(value) + + class YesNoFieldRenderer(CheckBoxFieldRenderer): def render_readonly(self, **kwargs):