3

I've used Flask Babel and have localized my project, but I have a problem with WTF forms, I can't translate the fields shown when field is empty. Any help?

This is working:

return jsonify({'error': gettext('Incorrect Data')}), 406

but when dealing with the Form class, Babel doesn't extract the field. like this:

class LoginForm(Form):
    username = TextField(gettext(u'Username'), validators=[validators.Required()])
    password = PasswordField('Password', validators=[validators.Required()])

I've tried both with/without the 'u' option

Machavity
  • 30,841
  • 27
  • 92
  • 100

2 Answers2

0

Messages for validator Required are set via Required(message=error_message), translate them with babel as well. Refer to WTForms documentation for more details.

class LoginForm(Form):
    username = TextField(gettext(u'Username'), validators=[validators.Required(message='Validation failed for username')])
    password = PasswordField('Password', validators=[validators.Required(message='Validation failed for password')])
wanderlust
  • 1,826
  • 1
  • 21
  • 25
  • I think there's a misunderstanding. I don't want to translate the messages. I want to translate the fields' placeholders. The items that are shown when the field is empty –  Jul 27 '15 at 10:02
  • In my case for localization I translate placeholders in python script, and send translated messages to html form, where use them in the following way: `{{form.name(placeholder=ui.get('login'))}}` where `form.name` is `wtforms.fields.StringField`, and `ui` is a dictionary with translated placeholders. – wanderlust Jul 27 '15 at 10:58
  • Not what I was expecting but it does the trick for me. Thanks –  Jul 27 '15 at 18:49
  • Can you please explain the ui dictionary? How do you define it? Where? –  Jul 27 '15 at 20:01
  • This is a simple dictionary, where I store my localized messages. It looks like: `ui = {'login': 'Ім’я користувача', 'password': 'Пароль'}` I prefer such type of localizing my projects. – wanderlust Jul 28 '15 at 06:31
0

try with lazy_gettext('').

class LoginForm(Form):
    username = TextField(lazy_gettext(u'Username'), validators=[validators.Required()])

in HTML:

{{form.username.label (class="form-control-label") }}
ascripter
  • 5,665
  • 12
  • 45
  • 68
Oj G
  • 39
  • 5