diff --git a/.gitignore b/.gitignore index c3457fb1..c6594ee9 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,4 @@ _build .idea/ htmlcov/ .cache/ +.vscode/ 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) 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'