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

1.5k views Asked by At

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.

2

There are 2 answers

0
Lawrence Liu On BEST ANSWER

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"),)
1
pafmaf On

My guess is that in your case gettext("logistic_amount") does not actually return the translated string.

As a rather crude 'quick fix' you could try using a custom admin/model/list.html for your model and: replace all occurrences of {{ name }} by {{ _(name) }}, then Jinja should take care of that. (Worked for me.)

I haven't looked into that but I believe thats some Babel / BabelEx configuration issue.

Regards