From 4b389322870396f9559463ea6da8d76370eee86a Mon Sep 17 00:00:00 2001 From: Martin Bierbaum Date: Wed, 12 Feb 2020 21:25:56 +0100 Subject: [PATCH 1/3] write test for DecimalField localization --- tests/test_i18n.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/tests/test_i18n.py b/tests/test_i18n.py index a2d5eae1..ad04fbf6 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -1,7 +1,7 @@ # coding=utf8 import pytest from flask import request -from wtforms import StringField +from wtforms import StringField, DecimalField from wtforms.validators import DataRequired, Length from flask_wtf import FlaskForm @@ -72,3 +72,30 @@ def test_outside_request(): sp = 'Field must be at least %(min)d character long.' assert translations.ngettext(ss, sp, 1) == ss assert translations.ngettext(ss, sp, 2) == sp + + +class NumberForm(FlaskForm): + + number = DecimalField(use_locale=True) + + +def test_decimal_field_localization(app): + try: + from flask_babel import Babel + except ImportError: + try: + from flask_babelex import Babel + except ImportError: + pytest.skip('Flask-Babel or Flask-BabelEx must be installed.') + + Babel(app) + + with app.test_request_context(): + app.config['BABEL_DEFAULT_LOCALE'] = 'de' + form = NumberForm(number=1100.1) + assert form['number']._value() == '1.100,1' + + with app.test_request_context(): + app.config['BABEL_DEFAULT_LOCALE'] = 'en' + form = NumberForm(number=1100.1) + assert form['number']._value() == '1,100.1' From b3e2f7339bdea15079882f9e796123b9e16a77e5 Mon Sep 17 00:00:00 2001 From: Martin Bierbaum Date: Wed, 12 Feb 2020 21:26:33 +0100 Subject: [PATCH 2/3] add locale property to FlaskForm.Meta --- flask_wtf/form.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/flask_wtf/form.py b/flask_wtf/form.py index 085d51ce..36bb37c5 100644 --- a/flask_wtf/form.py +++ b/flask_wtf/form.py @@ -12,7 +12,7 @@ from .csrf import _FlaskFormCSRF try: - from .i18n import translations + from .i18n import translations, get_locale except ImportError: translations = None # babel not installed @@ -33,6 +33,13 @@ class Meta(DefaultMeta): csrf_class = _FlaskFormCSRF csrf_context = session # not used, provided for custom csrf_class + @property + def locales(self): + if not current_app.config.get('WTF_I18N_ENABLED', True): + return False + locale = get_locale() + return [locale.language] + @cached_property def csrf(self): return current_app.config.get('WTF_CSRF_ENABLED', True) From d9c84fb527b0c5cecfc01fd1656db9cf4b1dd63f Mon Sep 17 00:00:00 2001 From: Martin Bierbaum Date: Wed, 12 Feb 2020 21:27:03 +0100 Subject: [PATCH 3/3] gitignore .vscode --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index c3457fb1..c6594ee9 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,4 @@ _build .idea/ htmlcov/ .cache/ +.vscode/