Django 1.8.2 文档

翻译

概述

为了让Django项目可翻译,你必须添加一些钩子到你的Python 代码和模板中。这些钩子叫做翻译字符串它们告诉Django:“如果这个文本的翻译可用,应该将它翻译成终端用户的语言。”你需要标记这些可翻译的字符串;系统只会翻译它知道的字符串。

Django 提供一些工具用于提取翻译字符串到消息文件中。这个文件方便翻译人员提供翻译字符串的目标语言。翻译人员填充完消息文件后,必须编译它。这个过程依赖GNU gettext 工具集。

完成这些事情之后,Django 将负责根据用户的语言偏好将网页翻译成对应的语言。

Django 的国际化钩子默认是打开的,这表示框架的某些地方已经有相关的I18N 钩子。如果你不需要使用国际化,你可以花两秒钟将在设置文件中设置USE_I18N = False这样的话,Django 将做一些优化而不加载国际化的机制。

还有一个独立但是相关的设置USE_L10N,它控制Django 是否应该实现本地化格式。更多信息参见本地化格式

确保你的项目已经启用翻译(最快的方法是检查MIDDLEWARE_CLASSES 是否包含django.middleware.locale.LocaleMiddleware)。如果还没有,请参见Django 如何发现语言偏好

国际化:在Python 代码中

标准的翻译

函数ugettext() 用于指定标准的翻译。习惯上会将它导入成一个别名 _ 以节省打字。

Python 的标准库gettext 模块将_() 安装进全局命名空间中,并作为gettext() 的别名。在Django 中,我们选择不遵守这个实践,原因有:

  1. 对国际化的字符集(Unicode)的支持,ugettext()gettext() 更有用。有时候,对于特定的文件,你应该使用ugettext_lazy() 作为默认的翻译方法。如果_() 不在全局命名空间中,开发人员必须想清楚哪一个是最合适的翻译函数。
  2. 下划线字符(_)在Python 的交互式shell 和doctest 测试中,用于表示“前一个结果”。安装全局的_() 函数会引起混乱。显式地导入ugettext()_() 将避免这个问题。

在下面的示例中,文本"Welcome to my site." 标记为一个翻译字符串:

from django.utils.translation import ugettext as _
from django.http import HttpResponse

def my_view(request):
    output = _("Welcome to my site.")
    return HttpResponse(output)

很明显,你可以不用别名来编写这段代码。下面的例子与前面完全一样:

from django.utils.translation import ugettext
from django.http import HttpResponse

def my_view(request):
    output = ugettext("Welcome to my site.")
    return HttpResponse(output)

翻译在计算生成的值上进行。下面的例子与前面两个完全一样:

def my_view(request):
    words = ['Welcome', 'to', 'my', 'site.']
    output = _(' '.join(words))
    return HttpResponse(output)

翻译可以在变量上进行。下面同样是一个完全一样的示例:

def my_view(request):
    sentence = 'Welcome to my site.'
    output = _(sentence)
    return HttpResponse(output)

(告诫使用变量或计算的值,如在前面的两个例子, 是Django的翻译字符串检测工具, django-admin makemessages, 将不能够找到这些字符串。 后面有makemessages 的更多信息)。

传递给_()ugettext() 的字符串可以通过Python 标准的命名字符串插值语法接收占位符。示例:

def my_view(request, m, d):
    output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
    return HttpResponse(output)

这种技术可以让语言相关的翻译重新排序。例如,英语翻译可能是"Today is November 26.",而西班牙语可能是"Hoy es 26 de Noviembre." —— 月份和天数的占位符交换位置了。

由于这个原因,每当有多个参数的时候,你都应该使用命名的字符串插值(例如,%(day)s)而不是位置插值(例如,%s%d)。如果使用位置插值,翻译将不能重新排序占位符。

给翻译人员的注释

如果你想给翻译人员一些提示,可以添加一个以Translators 为前缀的注释,例如:

def my_view(request):
    # Translators: This message appears on the home page only
    output = ugettext("Welcome to my site.")

这个注释会在生成的.po 文件中出现在可翻译的结构上方,而且可以在大部分翻译工具中显示出来。

只是为了完整性,下面是生成的.po 文件片段:

#. Translators: This message appears on the home page only
# path/to/python/file.py:123
msgid "Welcome to my site."
msgstr ""

它在模板中也可以工作。更多细节参见模板中给翻译人员的注释

标记字符串为no-op

django.utils.translation.ugettext_noop() 函数用于标记字符串为一个翻译字符串但是不用翻译它。该字符串将在后面依据一个变量翻译。

如果你的常量字符串需要在不同的系统和用户之间交互 —— 例如数据库中的字符串,它们应该保存在源语言中,但是需要在最后例如呈现给用户的时刻翻译,可以使用它。

多元化

函数django.utils.translation.ungettext() 用于指定多元化的消息。

ungettext 接收三个参数:单数形式的翻译字符串、复数形式的翻译字符串和对象的个数。

这个函数用于当你的Django 应用所要本地化的语言中,复数形式 比英语中的要复杂时(‘object’ 表示单数,‘objects’ 表示所有count 不等于一的情形,无论具体的值是多少)。

例如:

from django.utils.translation import ungettext
from django.http import HttpResponse

def hello_world(request, count):
    page = ungettext(
        'there is %(count)d object',
        'there are %(count)d objects',
    count) % {
        'count': count,
    }
    return HttpResponse(page)

这个例子中对象的数字作为count变量传递给翻译语言

需要注意的是多元化是复杂的,在每种语言的工作方式不同。 count 计数到1的比较并不总是正确的规则。此代码看起来复杂,但会产生某些语言不正确的结果:

from django.utils.translation import ungettext
from myapp.models import Report

count = Report.objects.count()
if count == 1:
    name = Report._meta.verbose_name
else:
    name = Report._meta.verbose_name_plural

text = ungettext(
    'There is %(count)d %(name)s available.',
    'There are %(count)d %(name)s available.',
    count
) % {
    'count': count,
    'name': name
}

不要尝试自己去实现单复数逻辑, 这样会出错。这种情况下, 可以考虑这么做:

text = ungettext(
    'There is %(count)d %(name)s object available.',
    'There are %(count)d %(name)s objects available.',
    count
) % {
    'count': count,
    'name': Report._meta.verbose_name,
}

注意

在使用 ungettext()的时候, 确保你你使用在每一个占位符中使用同一个名称。在上面的例子中, 你可以注意到我们是怎么在两种翻译中使用name这个变量的。 下面这个例子中, 除了在某些语言中会表达不正确之外, 还可能会造成错误:

text = ungettext(
    'There is %(count)d %(name)s available.',
    'There are %(count)d %(plural_name)s available.',
    count
) % {
    'count': Report.objects.count(),
    'name': Report._meta.verbose_name,
    'plural_name': Report._meta.verbose_name_plural
}

运行 django-admin compilemessages时,你会得到一个错误:

a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'

注意

复数形式和po文件

Django does not support custom plural equations in po files. As all translation catalogs are merged, only the plural form for the main Django po file (in django/conf/locale/<lang_code>/LC_MESSAGES/django.po) is considered. Plural forms in all other po files are ignored. Therefore, you should not use different plural equations in your project or application po files.

Contextual markers

Sometimes words have several meanings, such as "May" in English, which refers to a month name and to a verb. To enable translators to translate these words correctly in different contexts, you can use the django.utils.translation.pgettext() function, or the django.utils.translation.npgettext() function if the string needs pluralization. Both take a context string as the first variable.

In the resulting .po file, the string will then appear as often as there are different contextual markers for the same string (the context will appear on the msgctxt line), allowing the translator to give a different translation for each of them.

For example:

from django.utils.translation import pgettext

month = pgettext("month name", "May")

or:

from django.db import models
from django.utils.translation import pgettext_lazy

class MyThing(models.Model):
    name = models.CharField(help_text=pgettext_lazy(
        'help text for MyThing model', 'This is the help text'))

will appear in the .po file as:

msgctxt "month name"
msgid "May"
msgstr ""

Contextual markers are also supported by the trans and blocktrans template tags.

Lazy translation

Use the lazy versions of translation functions in django.utils.translation (easily recognizable by the lazy suffix in their names) to translate strings lazily – when the value is accessed rather than when they’re called.

These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering.

This is essential when calls to these functions are located in code paths that are executed at module load time.

This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases:

Model fields and relationships verbose_name

For example, to translate the help text of the name field in the following model, do the following:

from django.db import models
from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(help_text=_('This is the help text'))

You can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options:

class MyThing(models.Model):
    kind = models.ForeignKey(ThingKind, related_name='kinds',
                             verbose_name=_('kind'))

Just like you would do in verbose_name you should provide a lowercase verbose name text for the relation as Django will automatically titlecase it when required.

Model verbose names values

It is recommended to always provide explicit verbose_name and verbose_name_plural options rather than relying on the fallback English-centric and somewhat naïve determination of verbose names Django performs by looking at the model’s class name:

from django.db import models
from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(_('name'), help_text=_('This is the help text'))

    class Meta:
        verbose_name = _('my thing')
        verbose_name_plural = _('my things')

Model methods short_description

For model methods, you can provide translations to Django and the admin site with the short_description attribute:

from django.db import models
from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
    kind = models.ForeignKey(ThingKind, related_name='kinds',
                             verbose_name=_('kind'))

    def is_mouse(self):
        return self.kind.type == MOUSE_TYPE
    is_mouse.short_description = _('Is it a mouse?')

Working with lazy translation objects

The result of a ugettext_lazy() call can be used wherever you would use a unicode string (an object with type unicode) in Python. If you try to use it where a bytestring (a str object) is expected, things will not work as expected, since a ugettext_lazy() object doesn’t know how to convert itself to a bytestring. You can’t use a unicode string inside a bytestring, either, so this is consistent with normal Python behavior. For example:

# This is fine: putting a unicode proxy into a unicode string.
"Hello %s" % ugettext_lazy("people")

# This will not work, since you cannot insert a unicode object
# into a bytestring (nor can you insert our unicode proxy there)
b"Hello %s" % ugettext_lazy("people")

If you ever see output that looks like "hello <django.utils.functional...>", you have tried to insert the result of ugettext_lazy() into a bytestring. That’s a bug in your code.

If you don’t like the long ugettext_lazy name, you can just alias it as _ (underscore), like so:

from django.db import models
from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(help_text=_('This is the help text'))

Using ugettext_lazy() and ungettext_lazy() to mark strings in models and utility functions is a common operation. When you’re working with these objects elsewhere in your code, you should ensure that you don’t accidentally convert them to strings, because they should be converted as late as possible (so that the correct locale is in effect). This necessitates the use of the helper function described next.

Lazy translations and plural

When using lazy translation for a plural string ([u]n[p]gettext_lazy), you generally don’t know the number argument at the time of the string definition. Therefore, you are authorized to pass a key name instead of an integer as the number argument. Then number will be looked up in the dictionary under that key during string interpolation. Here’s example:

from django import forms
from django.utils.translation import ungettext_lazy

class MyForm(forms.Form):
    error_message = ungettext_lazy("You only provided %(num)d argument",
        "You only provided %(num)d arguments", 'num')

    def clean(self):
        # ...
        if error:
            raise forms.ValidationError(self.error_message % {'num': number})

If the string contains exactly one unnamed placeholder, you can interpolate directly with the number argument:

class MyForm(forms.Form):
    error_message = ungettext_lazy("You provided %d argument",
        "You provided %d arguments")

    def clean(self):
        # ...
        if error:
            raise forms.ValidationError(self.error_message % number)

Joining strings: string_concat()

Standard Python string joins (''.join([...])) will not work on lists containing lazy translation objects. Instead, you can use django.utils.translation.string_concat(), which creates a lazy object that concatenates its contents and converts them to strings only when the result is included in a string. For example:

from django.utils.translation import string_concat
from django.utils.translation import ugettext_lazy
...
name = ugettext_lazy('John Lennon')
instrument = ugettext_lazy('guitar')
result = string_concat(name, ': ', instrument)

In this case, the lazy translations in result will only be converted to strings when result itself is used in a string (usually at template rendering time).

Other uses of lazy in delayed translations

For any other case where you would like to delay the translation, but have to pass the translatable string as argument to another function, you can wrap this function inside a lazy call yourself. For example:

from django.utils import six  # Python 3 compatibility
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

mark_safe_lazy = lazy(mark_safe, six.text_type)

And then later:

lazy_string = mark_safe_lazy(_("<p>My <strong>string!</strong></p>"))

Localized names of languages

get_language_info()[source]

The get_language_info() function provides detailed information about languages:

>>> from django.utils.translation import get_language_info
>>> li = get_language_info('de')
>>> print(li['name'], li['name_local'], li['bidi'])
German Deutsch False

The name and name_local attributes of the dictionary contain the name of the language in English and in the language itself, respectively. The bidi attribute is True only for bi-directional languages.

The source of the language information is the django.conf.locale module. Similar access to this information is available for template code. See below.

国际化:在模板代码中

Django 模板 中的翻译使用两个模板标签,语法与Python 代码中使用的语法有稍许不同。为了让你的模板能够访问这些标签,需要将{% load i18n %} 放置在模板的顶部。和所有模板标签一样,这个标签需要在所有使用翻译的模板中加载,即使这些模板扩展自已经加载i18n 标签的模板。

trans template tag

{% trans %} 模板标签翻译一个常量字符串(位于单引号或双引号中)或变量:

<title>{% trans "This is the title." %}</title>
<title>{% trans myvar %}</title>

如果带有noop 选项,变量的查找仍然继续但是会忽略翻译。这对于需要在未来进行翻译的内容非常有用:

<title>{% trans "myvar" noop %}</title>

在内部,内联的翻译使用ugettext() 调用。

当一个模板变量(上面的myvar)传递给该标签时, 该标签会首先在运行时刻将变量解析成一个字符串,然后在消息目录中查找这个字符串。

{% trans %} 不可以将模板标签嵌入到字符串中。如果你的翻译字符串需要带有变量(占位符),可以使用{% blocktrans %}

如果你想提前翻译字符串但是不显示出来,你可以使用以下语法:

{% trans "This is the title" as the_title %}

<title>{{ the_title }}</title>
<meta name="description" content="{{ the_title }}">

实际应用中,你将使用它来获取字符串,然后在多处使用或者作为参数传递给其它模板标签或过滤器:

{% trans "starting point" as start %}
{% trans "end point" as end %}
{% trans "La Grande Boucle" as race %}

<h1>
  <a href="/" title="{% blocktrans %}Back to '{{ race }}' homepage{% endblocktrans %}">{{ race }}</a>
</h1>
<p>
{% for stage in tour_stages %}
    {% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br />{% else %}, {% endif %}
{% endfor %}
</p>

利用context 关键字,{% trans %} 还支持contextual markers

{% trans "May" context "month name" %}

blocktrans template tag

Contrarily to the trans tag, the blocktrans tag allows you to mark complex sentences consisting of literals and variable content for translation by making use of placeholders:

{% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}

To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples:

{% blocktrans with amount=article.price %}
That will cost $ {{ amount }}.
{% endblocktrans %}

{% blocktrans with myvar=value|filter %}
This will have {{ myvar }} inside.
{% endblocktrans %}

You can use multiple expressions inside a single blocktrans tag:

{% blocktrans with book_t=book|title author_t=author|title %}
This is {{ book_t }} by {{ author_t }}
{% endblocktrans %}

Note

The previous more verbose format is still supported: {% blocktrans with book|title as book_t and author|title as author_t %}

Other block tags (for example {% for %} or {% if %}) are not allowed inside a blocktrans tag.

If resolving one of the block arguments fails, blocktrans will fall back to the default language by deactivating the currently active language temporarily with the deactivate_all() function.

This tag also provides for pluralization. To use it:

  • Designate and bind a counter value with the name count. This value will be the one used to select the right plural form.
  • Specify both the singular and plural forms separating them with the {% plural %} tag within the {% blocktrans %} and {% endblocktrans %} tags.

An example:

{% blocktrans count counter=list|length %}
There is only one {{ name }} object.
{% plural %}
There are {{ counter }} {{ name }} objects.
{% endblocktrans %}

A more complex example:

{% blocktrans with amount=article.price count years=i.length %}
That will cost $ {{ amount }} per year.
{% plural %}
That will cost $ {{ amount }} per {{ years }} years.
{% endblocktrans %}

When you use both the pluralization feature and bind values to local variables in addition to the counter value, keep in mind that the blocktrans construct is internally converted to an ungettext call. This means the same notes regarding ungettext variables apply.

Reverse URL lookups cannot be carried out within the blocktrans and should be retrieved (and stored) beforehand:

{% url 'path.to.view' arg arg2 as the_url %}
{% blocktrans %}
This is a URL: {{ the_url }}
{% endblocktrans %}

{% blocktrans %} also supports contextual markers using the context keyword:

{% blocktrans with name=user.username context "greeting" %}Hi {{ name }}{% endblocktrans %}

Another feature {% blocktrans %} supports is the trimmed option. This option will remove newline characters from the beginning and the end of the content of the {% blocktrans %} tag, replace any whitespace at the beginning and end of a line and merge all lines into one using a space character to separate them. This is quite useful for indenting the content of a {% blocktrans %} tag without having the indentation characters end up in the corresponding entry in the PO file, which makes the translation process easier.

For instance, the following {% blocktrans %} tag:

{% blocktrans trimmed %}
  First sentence.
  Second paragraph.
{% endblocktrans %}

will result in the entry "First sentence. Second paragraph." in the PO file, compared to "   First sentence.   Second sentence. ", if the trimmed option had not been specified.

Changed in Django 1.7:

The trimmed option was added.

String literals passed to tags and filters

You can translate string literals passed as arguments to tags and filters by using the familiar _() syntax:

{% some_tag _("Page not found") value|yesno:_("yes,no") %}

In this case, both the tag and the filter will see the translated string, so they don’t need to be aware of translations.

Note

In this example, the translation infrastructure will be passed the string "yes,no", not the individual strings "yes" and "no". The translated string will need to contain the comma so that the filter parsing code knows how to split up the arguments. For example, a German translator might translate the string "yes,no" as "ja,nein" (keeping the comma intact).

Comments for translators in templates

Just like with Python code, these notes for translators can be specified using comments, either with the comment tag:

{% comment %}Translators: View verb{% endcomment %}
{% trans "View" %}

{% comment %}Translators: Short intro blurb{% endcomment %}
<p>{% blocktrans %}A multiline translatable
literal.{% endblocktrans %}</p>

or with the {# ... #} one-line comment constructs:


<button type="submit">{% trans "Go" %}</button>


{% blocktrans %}Ambiguous translatable block of text{% endblocktrans %}

Note

Just for completeness, these are the corresponding fragments of the resulting .po file:

#. Translators: View verb
# path/to/template/file.html:10
msgid "View"
msgstr ""

#. Translators: Short intro blurb
# path/to/template/file.html:13
msgid ""
"A multiline translatable"
"literal."
msgstr ""

# ...

#. Translators: Label of a button that triggers search
# path/to/template/file.html:100
msgid "Go"
msgstr ""

#. Translators: This is a text of the base template
# path/to/template/file.html:103
msgid "Ambiguous translatable block of text"
msgstr ""

Switching language in templates

If you want to select a language within a template, you can use the language template tag:

{% load i18n %}

{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<p>{% trans "Welcome to our page" %}</p>

{% language 'en' %}
    {% get_current_language as LANGUAGE_CODE %}
    <!-- Current language: {{ LANGUAGE_CODE }} -->
    <p>{% trans "Welcome to our page" %}</p>
{% endlanguage %}

While the first occurrence of “Welcome to our page” uses the current language, the second will always be in English.

Other tags

这些标签还需要{% load i18n %}

  • {% get_available_languages as LANGUAGES %} returns a list of tuples in which the first element is the language code and the second is the language name (translated into the currently active locale).
  • {% get_current_language as LANGUAGE_CODE %} 当前用户的首选语言,作为字符串。Example: en-us. (See How Django discovers language preference.)
  • {% get_current_language_bidi as LANGUAGE_BIDI %} 当前语言环境的方向。If True, it’s a right-to-left language, e.g.: Hebrew, Arabic. If False it’s a left-to-right language, e.g.: English, French, German etc.

If you enable the django.template.context_processors.i18n context processor then each RequestContext will have access to LANGUAGES, LANGUAGE_CODE, and LANGUAGE_BIDI as defined above.

Changed in Django 1.8:

The i18n context processor is not enabled by default for new projects.

You can also retrieve information about any of the available languages using provided template tags and filters. To get information about a single language, use the {% get_language_info %} tag:

{% get_language_info for LANGUAGE_CODE as lang %}
{% get_language_info for "pl" as lang %}

You can then access the information:

Language code: {{ lang.code }}<br />
Name of language: {{ lang.name_local }}<br />
Name in English: {{ lang.name }}<br />
Bi-directional: {{ lang.bidi }}

You can also use the {% get_language_info_list %} template tag to retrieve information for a list of languages (e.g. active languages as specified in LANGUAGES). See the section about the set_language redirect view for an example of how to display a language selector using {% get_language_info_list %}.

In addition to LANGUAGES style nested tuples, {% get_language_info_list %} supports simple lists of language codes. If you do this in your view:

context = {'available_languages': ['en', 'es', 'fr']}
return render(request, 'mytemplate.html', context)

you can iterate over those languages in the template:

{% get_language_info_list for available_languages as langs %}
{% for lang in langs %} ... {% endfor %}

There are also simple filters available for convenience:

  • {{ LANGUAGE_CODE|language_name }} (“German”)
  • {{ LANGUAGE_CODE|language_name_local }} (“Deutsch”)
  • {{ LANGUAGE_CODE|language_bidi }} (False)

Internationalization: in JavaScript code

Adding translations to JavaScript poses some problems:

  • JavaScript code doesn’t have access to a gettext implementation.
  • JavaScript code doesn’t have access to .po or .mo files; they need to be delivered by the server.
  • The translation catalogs for JavaScript should be kept as small as possible.

Django provides an integrated solution for these problems: It passes the translations into JavaScript, so you can call gettext, etc., from within JavaScript.

Thejavascript_catalog

javascript_catalog(request, domain='djangojs', packages=None)[source]

The main solution to these problems is the django.views.i18n.javascript_catalog() view, which sends out a JavaScript code library with functions that mimic the gettext interface, plus an array of translation strings. Those translation strings are taken from applications or Django core, according to what you specify in either the info_dict or the URL. Paths listed in LOCALE_PATHS are also included.

You hook it up like this:

from django.views.i18n import javascript_catalog

js_info_dict = {
    'packages': ('your.app.package',),
}

urlpatterns = [
    url(r'^jsi18n/$', javascript_catalog, js_info_dict),
]

Each string in packages should be in Python dotted-package syntax (the same format as the strings in INSTALLED_APPS) and should refer to a package that contains a locale directory. If you specify multiple packages, all those catalogs are merged into one catalog. This is useful if you have JavaScript that uses strings from different applications.

The precedence of translations is such that the packages appearing later in the packages argument have higher precedence than the ones appearing at the beginning, this is important in the case of clashing translations for the same literal.

By default, the view uses the djangojs gettext domain. This can be changed by altering the domain argument.

You can make the view dynamic by putting the packages into the URL pattern:

urlpatterns = [
    url(r'^jsi18n/(?P<packages>\S+?)/$', javascript_catalog),
]

With this, you specify the packages as a list of package names delimited by ‘+’ signs in the URL. This is especially useful if your pages use code from different apps and this changes often and you don’t want to pull in one big catalog file. As a security measure, these values can only be either django.conf or any package from the INSTALLED_APPS setting.

The JavaScript translations found in the paths listed in the LOCALE_PATHS setting are also always included. To keep consistency with the translations lookup order algorithm used for Python and templates, the directories listed in LOCALE_PATHS have the highest precedence with the ones appearing first having higher precedence than the ones appearing later.

Using the JavaScript translation catalog

To use the catalog, just pull in the dynamically generated script like this:

<script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script>

This uses reverse URL lookup to find the URL of the JavaScript catalog view. When the catalog is loaded, your JavaScript code can use the following methods:

  • gettext
  • ngettext
  • interpolate
  • get_format
  • gettext_noop
  • pgettext
  • npgettext
  • pluralidx

gettext

The gettext function behaves similarly to the standard gettext interface within your Python code:

document.write(gettext('this is to be translated'));

ngettext

The ngettext function provides an interface to pluralize words and phrases:

var object_count = 1 // or 0, or 2, or 3, ...
s = ngettext('literal for the singular case',
        'literal for the plural case', object_count);

interpolate

The interpolate function supports dynamically populating a format string. The interpolation syntax is borrowed from Python, so the interpolate function supports both positional and named interpolation:

  • Positional interpolation: obj contains a JavaScript Array object whose elements values are then sequentially interpolated in their corresponding fmt placeholders in the same order they appear. For example:

    fmts = ngettext('There is %s object. Remaining: %s',
            'There are %s objects. Remaining: %s', 11);
    s = interpolate(fmts, [11, 20]);
    // s is 'There are 11 objects. Remaining: 20'
    
  • Named interpolation: This mode is selected by passing the optional boolean named parameter as true. obj contains a JavaScript object or associative array. For example:

    d = {
        count: 10,
        total: 50
    };
    
    fmts = ngettext('Total: %(total)s, there is %(count)s object',
    'there are %(count)s of a total of %(total)s objects', d.count);
    s = interpolate(fmts, d, true);
    

You shouldn’t go over the top with string interpolation, though: this is still JavaScript, so the code has to make repeated regular-expression substitutions. This isn’t as fast as string interpolation in Python, so keep it to those cases where you really need it (for example, in conjunction with ngettext to produce proper pluralizations).

get_format

The get_format function has access to the configured i18n formatting settings and can retrieve the format string for a given setting name:

document.write(get_format('DATE_FORMAT'));
// 'N j, Y'

It has access to the following settings:

This is useful for maintaining formatting consistency with the Python-rendered values.

gettext_noop

This emulates the gettext function but does nothing, returning whatever is passed to it:

document.write(gettext_noop('this will not be translated'));

This is useful for stubbing out portions of the code that will need translation in the future.

pgettext

The pgettext function behaves like the Python variant (pgettext()), providing a contextually translated word:

document.write(pgettext('month name', 'May'));

npgettext

The npgettext function also behaves like the Python variant (npgettext()), providing a pluralized contextually translated word:

document.write(npgettext('group', 'party', 1));
// party
document.write(npgettext('group', 'party', 2));
// parties

pluralidx

The pluralidx function works in a similar way to the pluralize template filter, determining if a given count should use a plural form of a word or not:

document.write(pluralidx(0));
// true
document.write(pluralidx(1));
// false
document.write(pluralidx(2));
// true

In the simplest case, if no custom pluralization is needed, this returns false for the integer 1 and true for all other numbers.

However, pluralization is not this simple in all languages. If the language does not support pluralization, an empty value is provided.

Additionally, if there are complex rules around pluralization, the catalog view will render a conditional expression. This will evaluate to either a true (should pluralize) or false (should not pluralize) value.

Note on performance

The javascript_catalog() view generates the catalog from .mo files on every request. Since its output is constant — at least for a given version of a site — it’s a good candidate for caching.

Server-side caching will reduce CPU load. It’s easily implemented with the cache_page() decorator. To trigger cache invalidation when your translations change, provide a version-dependent key prefix, as shown in the example below, or map the view at a version-dependent URL.

from django.views.decorators.cache import cache_page
from django.views.i18n import javascript_catalog

# The value returned by get_version() must change when translations change.
@cache_page(86400, key_prefix='js18n-%s' % get_version())
def cached_javascript_catalog(request, domain='djangojs', packages=None):
    return javascript_catalog(request, domain, packages)

Client-side caching will save bandwidth and make your site load faster. If you’re using ETags (USE_ETAGS = True), you’re already covered. Otherwise, you can apply conditional decorators. In the following example, the cache is invalidated whenever you restart your application server.

from django.utils import timezone
from django.views.decorators.http import last_modified
from django.views.i18n import javascript_catalog

last_modified_date = timezone.now()

@last_modified(lambda req, **kw: last_modified_date)
def cached_javascript_catalog(request, domain='djangojs', packages=None):
    return javascript_catalog(request, domain, packages)

You can even pre-generate the JavaScript catalog as part of your deployment procedure and serve it as a static file. This radical technique is implemented in django-statici18n.

国际化:在URL模式中

Django提供了两种机制来国际化URL模式:

Warning

Using either one of these features requires that an active language be set for each request; in other words, you need to have django.middleware.locale.LocaleMiddleware in your MIDDLEWARE_CLASSES setting.

URL模式中的语言前缀

i18n_patterns(prefix, pattern_description, ...)[source]

Deprecated since version 1.8: The prefix argument to i18n_patterns() has been deprecated and will not be supported in Django 2.0. Simply pass a list of django.conf.urls.url() instances instead.

This function can be used in your root URLconf and Django will automatically prepend the current active language code to all url patterns defined within i18n_patterns(). Example URL patterns:

from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns

from about import views as about_views
from news import views as news_views
from sitemap.views import sitemap

urlpatterns = [
    url(r'^sitemap\.xml$', sitemap, name='sitemap_xml'),
]

news_patterns = [
    url(r'^$', news_views.index, name='index'),
    url(r'^category/(?P<slug>[\w-]+)/$', news_views.category, name='category'),
    url(r'^(?P<slug>[\w-]+)/$', news_views.details, name='detail'),
]

urlpatterns += i18n_patterns(
    url(r'^about/$', about_views.main, name='about'),
    url(r'^news/', include(news_patterns, namespace='news')),
)

After defining these URL patterns, Django will automatically add the language prefix to the URL patterns that were added by the i18n_patterns function. Example:

from django.core.urlresolvers import reverse
from django.utils.translation import activate

>>> activate('en')
>>> reverse('sitemap_xml')
'/sitemap.xml'
>>> reverse('news:index')
'/en/news/'

>>> activate('nl')
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
'/nl/news/news-slug/'

Warning

i18n_patterns() is only allowed in your root URLconf. Using it within an included URLconf will throw an ImproperlyConfigured exception.

Warning

Ensure that you don’t have non-prefixed URL patterns that might collide with an automatically-added language prefix.

Translating URL patterns

URL patterns can also be marked translatable using the ugettext_lazy() function. Example:

from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _

from about import views as about_views
from news import views as news_views
from sitemaps.views import sitemap

urlpatterns = [
    url(r'^sitemap\.xml$', sitemap, name='sitemap_xml'),
]

news_patterns = [
    url(r'^$', news_views.index, name='index'),
    url(_(r'^category/(?P<slug>[\w-]+)/$'), news_views.category, name='category'),
    url(r'^(?P<slug>[\w-]+)/$', news_views.details, name='detail'),
]

urlpatterns += i18n_patterns(
    url(_(r'^about/$'), about_views.main, name='about'),
    url(_(r'^news/'), include(news_patterns, namespace='news')),
)

After you’ve created the translations, the reverse() function will return the URL in the active language. Example:

from django.core.urlresolvers import reverse
from django.utils.translation import activate

>>> activate('en')
>>> reverse('news:category', kwargs={'slug': 'recent'})
'/en/news/category/recent/'

>>> activate('nl')
>>> reverse('news:category', kwargs={'slug': 'recent'})
'/nl/nieuws/categorie/recent/'

Warning

In most cases, it’s best to use translated URLs only within a language-code-prefixed block of patterns (using i18n_patterns()), to avoid the possibility that a carelessly translated URL causes a collision with a non-translated URL pattern.

Reversing in templates

If localized URLs get reversed in templates they always use the current language. To link to a URL in another language use the language template tag. It enables the given language in the enclosed template section:

{% load i18n %}

{% get_available_languages as languages %}

{% trans "View this category in:" %}
{% for lang_code, lang_name in languages %}
    {% language lang_code %}
    <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
    {% endlanguage %}
{% endfor %}

The language tag expects the language code as the only argument.

Localization: how to create language files

Once the string literals of an application have been tagged for later translation, the translation themselves need to be written (or obtained). Here’s how that works.

Message files

The first step is to create a message file for a new language. A message file is a plain-text file, representing a single language, that contains all available translation strings and how they should be represented in the given language. Message files have a .po file extension.

Django comes with a tool, django-admin makemessages, that automates the creation and upkeep of these files.

Gettext utilities

The makemessages command (and compilemessages discussed later) use commands from the GNU gettext toolset: xgettext, msgfmt, msgmerge and msguniq.

The minimum version of the gettext utilities supported is 0.15.

To create or update a message file, run this command:

django-admin makemessages -l de

...where de is the locale name for the message file you want to create. For example, pt_BR for Brazilian Portuguese, de_AT for Austrian German or id for Indonesian.

The script should be run from one of two places:

  • The root directory of your Django project (the one that contains manage.py).
  • The root directory of one of your Django apps.

The script runs over your project source tree or your application source tree and pulls out all strings marked for translation (see How Django discovers translations and be sure LOCALE_PATHS is configured correctly). It creates (or updates) a message file in the directory locale/LANG/LC_MESSAGES. In the de example, the file will be locale/de/LC_MESSAGES/django.po.

Changed in Django 1.7:

When you run makemessages from the root directory of your project, the extracted strings will be automatically distributed to the proper message files. That is, a string extracted from a file of an app containing a locale directory will go in a message file under that directory. A string extracted from a file of an app without any locale directory will either go in a message file under the directory listed first in LOCALE_PATHS or will generate an error if LOCALE_PATHS is empty.

By default django-admin makemessages examines every file that has the .html or .txt file extension. In case you want to override that default, use the --extension or -e option to specify the file extensions to examine:

django-admin makemessages -l de -e txt

Separate multiple extensions with commas and/or use -e or --extension multiple times:

django-admin makemessages -l de -e html,txt -e xml

Warning

When creating message files from JavaScript source code you need to use the special ‘djangojs’ domain, not -e js.

Using Jinja2 templates?

makemessages doesn’t understand the syntax of Jinja2 templates. To extract strings from a project containing Jinja2 templates, use Babel instead.

Here’s an example babel.cfg configuration file:

# Extraction from Python source files
[python: **.py]

# Extraction from Jinja2 templates
[jinja2: **.jinja]
extensions = jinja2.ext.with_

Make sure you list all extensions you’re using! Otherwise Babel won’t recognize the tags defined by these extensions and will ignore Jinja2 templates containing them entirely.

Babel provides similar features to makemessages, can replace it in general, and doesn’t depend on gettext. For more information, read its documentation about working with message catalogs.

No gettext?

If you don’t have the gettext utilities installed, makemessages will create empty files. If that’s the case, either install the gettext utilities or just copy the English message file (locale/en/LC_MESSAGES/django.po) if available and use it as a starting point; it’s just an empty translation file.

Working on Windows?

If you’re using Windows and need to install the GNU gettext utilities so makemessages works, see gettext on Windows for more information.

The format of .po files is straightforward. Each .po file contains a small bit of metadata, such as the translation maintainer’s contact information, but the bulk of the file is a list of messages – simple mappings between translation strings and the actual translated text for the particular language.

For example, if your Django app contained a translation string for the text "Welcome to my site.", like so:

_("Welcome to my site.")

...then django-admin makemessages will have created a .po file containing the following snippet – a message:

#: path/to/python/module.py:23
msgid "Welcome to my site."
msgstr ""

A quick explanation:

  • msgid is the translation string, which appears in the source. Don’t change it.
  • msgstr is where you put the language-specific translation. It starts out empty, so it’s your responsibility to change it. Make sure you keep the quotes around your translation.
  • As a convenience, each message includes, in the form of a comment line prefixed with # and located above the msgid line, the filename and line number from which the translation string was gleaned.

Long messages are a special case. There, the first string directly after the msgstr (or msgid) is an empty string. Then the content itself will be written over the next few lines as one string per line. Those strings are directly concatenated. Don’t forget trailing spaces within the strings; otherwise, they’ll be tacked together without whitespace!

Mind your charset

Due to the way the gettext tools work internally and because we want to allow non-ASCII source strings in Django’s core and your applications, you must use UTF-8 as the encoding for your PO files (the default when PO files are created). This means that everybody will be using the same encoding, which is important when Django processes the PO files.

To reexamine all source code and templates for new translation strings and update all message files for all languages, run this:

django-admin makemessages -a

Compiling message files

After you create your message file – and each time you make changes to it – you’ll need to compile it into a more efficient form, for use by gettext. Do this with the django-admin compilemessages utility.

This tool runs over all available .po files and creates .mo files, which are binary files optimized for use by gettext. In the same directory from which you ran django-admin makemessages, run django-admin compilemessages like this:

django-admin compilemessages

That’s it. Your translations are ready for use.

Working on Windows?

If you’re using Windows and need to install the GNU gettext utilities so django-admin compilemessages works see gettext on Windows for more information.

.po files: Encoding and BOM usage.

Django only supports .po files encoded in UTF-8 and without any BOM (Byte Order Mark) so if your text editor adds such marks to the beginning of files by default then you will need to reconfigure it.

Creating message files from JavaScript source code

You create and update the message files the same way as the other Django message files – with the django-admin makemessages tool. The only difference is you need to explicitly specify what in gettext parlance is known as a domain in this case the djangojs domain, by providing a -d djangojs parameter, like this:

django-admin makemessages -d djangojs -l de

This would create or update the message file for JavaScript for German. After updating message files, just run django-admin compilemessages the same way as you do with normal Django message files.

gettext on Windows

This is only needed for people who either want to extract message IDs or compile message files (.po). Translation work itself just involves editing existing files of this type, but if you want to create your own message files, or want to test or compile a changed message file, you will need the gettext utilities:

  • Download the following zip files from the GNOME servers https://download.gnome.org/binaries/win32/dependencies/

    • gettext-runtime-X.zip
    • gettext-tools-X.zip

    X is the version number, we are requiring 0.15 or higher.

  • Extract the contents of the bin directories in both files to the same folder on your system (i.e. C:Program Filesgettext-utils)

  • Update the system PATH:

    • Control Panel > System > Advanced > Environment Variables.
    • In the System variables list, click Path, click Edit.
    • Add ;C:Program Filesgettext-utilsin at the end of the Variable value field.

You may also use gettext binaries you have obtained elsewhere, so long as the xgettext --version command works properly. Do not attempt to use Django translation utilities with a gettext package if the command xgettext --version entered at a Windows command prompt causes a popup window saying “xgettext.exe has generated errors and will be closed by Windows”.

Customizing the makemessages

If you want to pass additional parameters to xgettext, you need to create a custom makemessages command and override its xgettext_options attribute:

from django.core.management.commands import makemessages

class Command(makemessages.Command):
    xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']

If you need more flexibility, you could also add a new argument to your custom makemessages command:

from django.core.management.commands import makemessages

class Command(makemessages.Command):

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument('--extra-keyword', dest='xgettext_keywords',
                            action='append')

    def handle(self, *args, **options):
        xgettext_keywords = options.pop('xgettext_keywords')
        if xgettext_keywords:
            self.xgettext_options = (
                makemessages.Command.xgettext_options[:] +
                ['--keyword=%s' % kwd for kwd in xgettext_keywords]
            )
        super(Command, self).handle(*args, **options)

Miscellaneous

The set_language

set_language(request)[source]

方便起见, Django自带了一个, django.views.i18n.set_language()视图, 作用是设置用户语言偏好并重定向返回到前一页面

在URLconf中加入下面这行代码来激活这个视图:

url(r'^i18n/', include('django.conf.urls.i18n')),

(注意这个例子使得这个视图在/i18n/setlang/中有效.)

Warning

Make sure that you don’t include the above URL within i18n_patterns() - it needs to be language-independent itself to work correctly.

The view expects to be called via the POST method, with a language parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. Otherwise, it saves the language choice in a cookie that is by default named django_language. (The name can be changed through the LANGUAGE_COOKIE_NAME setting.)

After setting the language choice, Django redirects the user, following this algorithm:

  • Django looks for a next parameter in the POST data.
  • If that doesn’t exist, or is empty, Django tries the URL in the Referrer header.
  • If that’s empty – say, if a user’s browser suppresses that header – then the user will be redirected to / (the site root) as a fallback.

Here’s example HTML template code:

{% load i18n %}
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
    {{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>

In this example, Django looks up the URL of the page to which the user will be redirected in the redirect_to context variable.

明确设定使用语言

You may want to set the active language for the current session explicitly. Perhaps a user’s language preference is retrieved from another system, for example. You’ve already been introduced to django.utils.translation.activate(). That applies to the current thread only. To persist the language for the entire session, also modify LANGUAGE_SESSION_KEY in the session:

from django.utils import translation
user_language = 'fr'
translation.activate(user_language)
request.session[translation.LANGUAGE_SESSION_KEY] = user_language

You would typically want to use both: django.utils.translation.activate() will change the language for this thread, and modifying the session makes this preference persist in future requests.

If you are not using sessions, the language will persist in a cookie, whose name is configured in LANGUAGE_COOKIE_NAME. For example:

from django.utils import translation
from django import http
from django.conf import settings
user_language = 'fr'
translation.activate(user_language)
response = http.HttpResponse(...)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)

Using translations outside views and templates

While Django provides a rich set of i18n tools for use in views and templates, it does not restrict the usage to Django-specific code. The Django translation mechanisms can be used to translate arbitrary texts to any language that is supported by Django (as long as an appropriate translation catalog exists, of course). You can load a translation catalog, activate it and translate text to language of your choice, but remember to switch back to original language, as activating a translation catalog is done on per-thread basis and such change will affect code running in the same thread.

For example:

from django.utils import translation

def welcome_translated(language):
    cur_language = translation.get_language()
    try:
        translation.activate(language)
        text = translation.ugettext('welcome')
    finally:
        translation.activate(cur_language)
    return text

Calling this function with the value ‘de’ will give you "Willkommen", regardless of LANGUAGE_CODE and language set by middleware.

Functions of particular interest are django.utils.translation.get_language() which returns the language used in the current thread, django.utils.translation.activate() which activates a translation catalog for the current thread, and django.utils.translation.check_for_language() which checks if the given language is supported by Django.

To help write more concise code, there is also a context manager django.utils.translation.override() that stores the current language on enter and restores it on exit. With it, the above example becomes:

from django.utils import translation

def welcome_translated(language):
    with translation.override(language):
        return translation.ugettext('welcome')

实现细节

Django 翻译的特点

Django 的翻译机制使用Python 自带的gettext 模块。如果你了解gettext,你应该注意到Django 翻译方式的这些特点:

  • 字符串域是djangodjangojs这个字符串域用于区分不同的而程序,这些程序将它们的数据保存在共同的消息文件库中(通常是/usr/share/locale/)。django 域用于Python 和模板的翻译字符串,而且还会加载到全局翻译目录中。djangojs 域只用于JavaScript 的翻译目录,以确保它尽可能的小。
  • Django 没有单独使用xgettext它使用Python 对xgettextmsgfmt 进行的封装。最主要是为了方便。

Django 如何发现语言偏好

一旦你准备好翻译,或者你只是想使用Django 自带的翻译,你需要为你的应用启用翻译。

在后台,Django 有一个非常灵活的模型决定应该使用哪种语言 —— 所有用户还是特定的用户,或者两种都可以。

To set an installation-wide language preference, set LANGUAGE_CODE. Django uses this language as the default translation – the final attempt if no better matching translation is found through one of the methods employed by the locale middleware (see below).

If all you want is to run Django with your native language all you need to do is set LANGUAGE_CODE and make sure the corresponding message files and their compiled versions (.mo) exist.

如果你想让每个用户指定首选语言,那么你还要 使用 LocaleMiddleware. LocaleMiddleware 会打开基于请求数据的语言选择。它为每个人用户的内容进行个性化。

To use LocaleMiddleware, add 'django.middleware.locale.LocaleMiddleware' to your MIDDLEWARE_CLASSES setting. Because middleware order matters, you should follow these guidelines:

  • Make sure it’s one of the first middlewares installed.
  • It should come after SessionMiddleware, because LocaleMiddleware makes use of session data. And it should come before CommonMiddleware because CommonMiddleware needs an activated language in order to resolve the requested URL.
  • If you use CacheMiddleware, put LocaleMiddleware after it.

例如,你的MIDDLEWARE_CLASSES也许看起来像这样子

MIDDLEWARE_CLASSES = (
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.locale.LocaleMiddleware',
   'django.middleware.common.CommonMiddleware',
)

(For more on middleware, see the middleware documentation.)

LocaleMiddleware tries to determine the user’s language preference by following this algorithm:

  • First, it looks for the language prefix in the requested URL. This is only performed when you are using the i18n_patterns function in your root URLconf. See Internationalization: in URL patterns for more information about the language prefix and how to internationalize URL patterns.

  • Failing that, it looks for the LANGUAGE_SESSION_KEY key in the current user’s session.

    Changed in Django 1.7:

    In previous versions, the key was named django_language, and the LANGUAGE_SESSION_KEY constant did not exist.

  • Failing that, it looks for a cookie.

    The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.)

  • Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations.

  • Failing that, it uses the global LANGUAGE_CODE setting.

Notes:

  • In each of these places, the language preference is expected to be in the standard language format, as a string. For example, Brazilian Portuguese is pt-br.

  • If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies de-at (Austrian German) but Django only has de available, Django uses de.

  • Only languages listed in the LANGUAGES setting can be selected. If you want to restrict the language selection to a subset of provided languages (because your application doesn’t provide all those languages), set LANGUAGES to a list of languages. For example:

    LANGUAGES = (
      ('de', _('German')),
      ('en', _('English')),
    )
    

    This example restricts languages that are available for automatic selection to German and English (and any sublanguage, like de-ch or en-us).

  • If you define a custom LANGUAGES setting, as explained in the previous bullet, you can mark the language names as translation strings – but use ugettext_lazy() instead of ugettext() to avoid a circular import.

    Here’s a sample settings file:

    from django.utils.translation import ugettext_lazy as _
    
    LANGUAGES = (
        ('de', _('German')),
        ('en', _('English')),
    )
    

Once LocaleMiddleware determines the user’s preference, it makes this preference available as request.LANGUAGE_CODE for each HttpRequest. Feel free to read this value in your view code. Here’s a simple example:

from django.http import HttpResponse

def hello_world(request, count):
    if request.LANGUAGE_CODE == 'de-at':
        return HttpResponse("You prefer to read Austrian German.")
    else:
        return HttpResponse("You prefer to read another language.")

Note that, with static (middleware-less) translation, the language is in settings.LANGUAGE_CODE, while with dynamic (middleware) translation, it’s in request.LANGUAGE_CODE.

Django是如何找到翻译文件的

At runtime, Django builds an in-memory unified catalog of literals-translations. To achieve this it looks for translations by following this algorithm regarding the order in which it examines the different file paths to load the compiled message files (.mo) and the precedence of multiple translations for the same literal:

  1. The directories listed in LOCALE_PATHS have the highest precedence, with the ones appearing first having higher precedence than the ones appearing later.
  2. Then, it looks for and uses if it exists a locale directory in each of the installed apps listed in INSTALLED_APPS. The ones appearing first have higher precedence than the ones appearing later.
  3. Finally, the Django-provided base translation in django/conf/locale is used as a fallback.

See also

The translations for literals included in JavaScript assets are looked up following a similar but not identical algorithm. See the javascript_catalog view documentation for more details.

In all cases the name of the directory containing the translation is expected to be named using locale name notation. E.g. de, pt_BR, es_AR, etc.

This way, you can write applications that include their own translations, and you can override base translations in your project. Or, you can just build a big project out of several apps and put all translations into one big common message file specific to the project you are composing. The choice is yours.

All message file repositories are structured the same way. They are:

  • All paths listed in LOCALE_PATHS in your settings file are searched for <language>/LC_MESSAGES/django.(po|mo)
  • $APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)
  • $PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)

To create message files, you use the django-admin makemessages tool. And you use django-admin compilemessages to produce the binary .mo files that are used by gettext.

You can also run django-admin compilemessages --settings=path.to.settings to make the compiler process all the directories in your LOCALE_PATHS setting.