从Django * .po / mo文件获取翻译的正确方法是什么?

时间:2019-12-04 17:20:59

标签: python django python-3.x localization translation

我需要将所有选择的译文发送到前端。目前,我activate每种语言,然后使用ugettext,但看起来很丑。

from django.conf import settings
from django.utils.translation import activate, ugettext

# settings.LANGUAGES looks like:
settings.LANGUAGES = [
    ('en', 'English'),
    ('ru', 'Russian')
]

class Profile(models.Model):
    ACTIVE = 1
    INACTIVE = 2
    CLOSED = 3
    PROFILE_STATUS_CHOICES = (
        (ACTIVE, _('Active')),
        (INACTIVE, _('Inactive')),
        (CLOSED, _('Closed')),
)

def choices_serialize(choices):
    """
    Convert choices to format suitable for Front End's tree-select.

    :param choices:
    :return: [{'id': 1, 'text': {'en': 'Active', 'ru': 'Действующий'}},
              {'id': 2, 'text': {'en': 'Inactive','ru': 'Недействующий'}},
              {'id': 3, 'text': {'en': 'Closed', 'ru': 'Закрыт'}}]
    """

    data = {}

    for lang in [t[0] for t in settings.LANGUAGES]:
        activate(lang)

        for choice in choices:
            data.setdefault(choice[0], {})
            data[choice[0]].setdefault(lang, ugettext(choice[1]))

    return [{'id': k, 'text': v} for k, v in data.items()]

choices_serialize(Profile.PROFILE_STATUS_CHOICES)

有更好的方法吗?

0 个答案:

没有答案