Search code examples
pythonflaskflask-admin

How to translate field label automatically when using flask-admin?


I would like to know how to use Flask-BabelEx(which is recommended by Flask-Admin) to translate field labels automatically when it's been generated by flask-admin.

For example, If I have a field which is defined as below:

class PurchaseOrder(Base):
    __tablename__ = 'purchase_order'
    id = Column(Integer, primary_key=True)
    logistic_amount = Column(Numeric(xxxx))

    def __unicode__(self):
        return self.id

And the view is defiend as

class PurchaseOrderAdmin(ModelView):
    column_labels = dict(logistic_amount=gettext("logistic_amount"),)

Then register to the admin as below:

    admin.add_view(PurchaseOrderAdmin(PurchaseOrder, db_session, category='Order'))

Here is how I init babel:

babel = Babel(app, default_locale="zh_CN", default_timezone="CST")

@babel.localeselector
def get_locale():
    override = request.args.get('lang')
    if override:
        session['lang'] = override
    return session.get('lang', 'zh_CN')

And I have generated the follow files:

translations/zh_CN/LC_MESSAGES/messages.mo
translations/zh_CN/LC_MESSAGES/messages.po

Content of file messages.po shown below:

msgid ""
msgstr ""
msgid "logistic_amount"
msgstr "物流费用"

But seems the key(logistic_amount) rather than the translated string(物流费用) is displaying in the list and edit page all the time.

Is there any piece missing here?

Thanks for the help.


Solution

  • We need to use lazy_gettext rather than gettext to make it work, examples as below:

    adminViews.add_view(SalesOrderAdmin(SalesOrder, db_session, name=lazy_gettext("Sales Order")))
    

    And

    class PurchaseOrderAdmin(ModelView):
        column_labels = dict(logistic_amount=lazy_gettext("logistic_amount"),)