pythonflaskflask-wtformspython-babel

Flask WTF localization with Babel


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


Solution

  • 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')])