Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add locales as a property to FlaskForm.Meta #399

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ _build
.idea/
htmlcov/
.cache/
.vscode/
9 changes: 8 additions & 1 deletion flask_wtf/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down
29 changes: 28 additions & 1 deletion tests/test_i18n.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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'