Search code examples
pythonflaskflask-wtformspython-babelflask-babel

How to use Flask-Babel gettext in Flask-WTForms render_kw?


I'm starting using Babel with WTForms and Flask. Below I try to gettext the placeholder keywords for my Username and Password fields :

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask_babel import gettext
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired


class LoginForm(FlaskForm):
    username = StringField(label='username',
                           validators=[DataRequired()],
                           render_kw={"placeholder": gettext('Username')})
    password = PasswordField(label='password',
                             validators=[DataRequired()],
                             render_kw={"placeholder": gettext('Password')})

Here is my French .po file (which has of course been compiled) :

# French (France) translations for PROJECT.
# Copyright (C) 2017 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2017.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2017-11-20 12:08+0100\n"
"PO-Revision-Date: 2017-11-20 12:10+0100\n"
"Language: fr_FR\n"
"Language-Team: fr_FR <[email protected]>\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.5.1\n"
"Last-Translator: \n"
"X-Generator: Poedit 2.0.4\n"

#: app/forms.py:13
msgid "Username"
msgstr "Nom d’utilisateur"

#: app/forms.py:16
msgid "Password"
msgstr "Mot de passe"

#: app/templates/login.html:34
msgid "Login"
msgstr "Se connecter"

Unfortunately, even when I force the locale in French those two fields stay in English. I made it work for the Login translation in my Jinja2 template.

Did I write something wrong ?


Solution

  • i think you should use lazy_gettext() method