国际化简介

配置

settings.py

from django.utils.translation import ugettext_lazy as _

USE_I18N = True  # Enable Internationalization
LANGUAGE_CODE = 'en'  # Language in which original texts are written
LANGUAGES = [  # Available languages
    ('en', _("English")),
    ('de', _("German")),
    ('fr', _("French")),
]

# Make sure the LocaleMiddleware is included, AFTER SessionMiddleware
# and BEFORE middlewares using internationalization (such as CommonMiddleware)
MIDDLEWARE_CLASSES = [
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.locale.LocaleMiddleware',
   'django.middleware.common.CommonMiddleware',
]

将字符串标记为可翻译

翻译的第一步是将字符串标记为可翻译。这是通过其中一个 gettext 函数传递它们(请参阅语法部分 )。例如,这是一个示例模型定义:

from django.utils.translation import ugettext_lazy as _
# It is common to import gettext as the shortcut `_` as it is often used
# several times in the same file.

class Child(models.Model):

    class Meta:
        verbose_name = _("child")
        verbose_name_plural = _("children")

    first_name = models.CharField(max_length=30, verbose_name=_("first name"))
    last_name = models.CharField(max_length=30, verbose_name=_("last name"))
    age = models.PositiveSmallIntegerField(verbose_name=_("age"))

封装在 _() 中的所有字符串现在都标记为可翻译。打印时,它们将始终显示为封装的字符串,无论选择何种语言(因为还没有可用的翻译)。

翻译字符串

这个例子足以开始翻译。大多数情况下,你只希望将字符串标记为可翻译,以预测项目的预期国际化。因此,这在另一个例子中有所涉及。