From eb275ca7a4b703e8e527c35e9e918efc0fb7fab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Wed, 31 Oct 2018 12:06:20 +0100 Subject: [PATCH] misc: add a |decimal template tag (#27699) --- tests/test_templates.py | 9 +++++++++ wcs/qommon/templatetags/qommon.py | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/tests/test_templates.py b/tests/test_templates.py index 2dd043cf5..059a617fa 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -141,3 +141,12 @@ def test_datetime_templatetags(): def test_variable_unicode_error_handling(): tmpl = Template('{{ form_var_éléphant }}') assert tmpl.render() == '' + +def test_decimal_templatetag(): + tmpl = Template('{{ plop|decimal }}') + assert tmpl.render({'plop': 'toto'}) == '' + assert tmpl.render({'plop': '3.14'}) == '3.14' + assert tmpl.render({'plop': '3,14'}) == '3.14' + assert tmpl.render({'plop': 3.14}) == '3.14' + assert tmpl.render({'plop': 12345.678}) == '12345.678' + assert tmpl.render({'plop': None}) == '' diff --git a/wcs/qommon/templatetags/qommon.py b/wcs/qommon/templatetags/qommon.py index 4b65fd938..2711a8a7c 100644 --- a/wcs/qommon/templatetags/qommon.py +++ b/wcs/qommon/templatetags/qommon.py @@ -15,6 +15,7 @@ # along with this program; if not, see . import datetime +from decimal import Decimal from django import template from django.template import defaultfilters @@ -75,6 +76,18 @@ def date(value, arg=None): value = parse_date(value) return defaultfilters.date(value, arg=arg) +@register.filter(is_safe=True) +def decimal(value): + if not value: + return '' + try: + if isinstance(value, basestring): + # replace , by . for French users confort + value = value.replace(',', '.') + return Decimal(value).quantize(Decimal('1.0000')).normalize() + except ArithmeticError: + return '' + @register.simple_tag def standard_text(text_id): return mark_safe(TextsDirectory.get_html_text(str(text_id))) -- 2.19.1