In order to make a Django project translatable, you have to add a minimal
number of hooks to your Python code and templates. These hooks are called
translation strings. They tell Django: “This text
should be translated into the end user’s language, if a translation for this
text is available in that language.” It’s your responsibility to mark
translatable strings; the system can only translate strings it knows about.

Django then provides utilities to extract the translation strings into a
message file. This file is a convenient way for translators to provide
the equivalent of the translation strings in the target language. Once the
translators have filled in the message file, it must be compiled. This process
relies on the GNU gettext toolset.

Once this is done, Django takes care of translating Web apps on the fly in each
available language, according to users’ language preferences.

Django’s internationalization hooks are on by default, and that means there’s a
bit of i18n-related overhead in certain places of the framework. If you don’t
use internationalization, you should take the two seconds to set
USE_I18N=False in your settings file. Then Django will
make some optimizations so as not to load the internationalization machinery.
You’ll probably also want to remove 'django.core.context_processors.i18n'
from your TEMPLATE_CONTEXT_PROCESSORS setting.

Note

There is also an independent but related USE_L10N setting that
controls if Django should implement format localization. See
Format localization for more details.

Specify a translation string by using the function
ugettext(). It’s convention to import this
as a shorter alias, _, to save typing.

Note

Python’s standard library gettext module installs _() into the
global namespace, as an alias for gettext(). In Django, we have chosen
not to follow this practice, for a couple of reasons:

For international character set (Unicode) support,
ugettext() is more useful than
gettext(). Sometimes, you should be using
ugettext_lazy() as the default
translation method for a particular file. Without _() in the
global namespace, the developer has to think about which is the
most appropriate translation function.

The underscore character (_) is used to represent “the previous
result” in Python’s interactive shell and doctest tests. Installing a
global _() function causes interference. Explicitly importing
ugettext() as _() avoids this problem.

In this example, the text "Welcometomysite." is marked as a translation
string:

(The caveat with using variables or computed values, as in the previous two
examples, is that Django’s translation-string-detecting utility,
django-admin.pymakemessages, won’t be able to find
these strings. More on makemessages later.)

The strings you pass to _() or ugettext() can take placeholders,
specified with Python’s standard named-string interpolation syntax. Example:

defmy_view(request,m,d):output=_('Today is %(month)s%(day)s.')%{'month':m,'day':d}returnHttpResponse(output)

This technique lets language-specific translations reorder the placeholder
text. For example, an English translation may be "TodayisNovember26.",
while a Spanish translation may be "Hoyes26deNoviembre." – with the
month and the day placeholders swapped.

For this reason, you should use named-string interpolation (e.g., %(day)s)
instead of positional interpolation (e.g., %s or %d) whenever you
have more than a single parameter. If you used positional interpolation,
translations wouldn’t be able to reorder placeholder text.

Use this if you have constant strings that should be stored in the source
language because they are exchanged over systems or users – such as strings
in a database – but should be translated at the last possible point in time,
such as when the string is presented to the user.

ungettext takes three arguments: the singular translation string, the plural
translation string and the number of objects.

This function is useful when you need your Django application to be localizable
to languages where the number and complexity of plural forms is
greater than the two forms used in English (‘object’ for the singular and
‘objects’ for all the cases where count is different from one, irrespective
of its value.)

In this example the number of objects is passed to the translation
languages as the count variable.

Note that pluralization is complicated and works differently in each language.
Comparing count to 1 isn’t always the correct rule. This code looks
sophisticated, but will produce incorrect results for some languages:

When using ungettext(), make sure you use a single name for every
extrapolated variable included in the literal. In the examples above, note
how we used the name Python variable in both translation strings. This
example, besides being incorrect in some languages as noted above, would
fail:

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

Note

Plural form and po files

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.

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.

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:

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:

fromdjango.dbimportmodelsfromdjango.utils.translationimportugettext_lazyas_classMyThing(models.Model):name=models.CharField(_('name'),help_text=_('This is the help text'))classMeta:verbose_name=_('my thing')verbose_name_plural=_('my things')

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

fromdjango.dbimportmodelsfromdjango.utils.translationimportugettext_lazyas_classMyThing(models.Model):kind=models.ForeignKey(ThingKind,related_name='kinds',verbose_name=_('kind'))defis_mouse(self):returnself.kind.type==MOUSE_TYPEis_mouse.short_description=_('Is it a mouse?')

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.u"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)"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:

fromdjango.dbimportmodelsfromdjango.utils.translationimportugettext_lazyas_classMyThing(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.

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:

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:

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:

Translations in Django templates uses two template
tags and a slightly different syntax than in Python code. To give your template
access to these tags, put {%loadi18n%} toward the top of your template.
As with all template tags, this tag needs to be loaded in all templates which
use translations, even those templates that extend from other templates which
have already loaded the i18n 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:

{%blocktranswithamount=article.price%}
That will cost $ {{amount}}.
{%endblocktrans%}{%blocktranswithmyvar=value|filter%}
This will have {{myvar}} inside.
{%endblocktrans%}

You can use multiple expressions inside a single blocktrans tag:

{%blocktranswithbook_t=book|titleauthor_t=author|title%}
This is {{book_t}} by {{author_t}}{%endblocktrans%}

Note

The previous more verbose format is still supported:
{%blocktranswithbook|titleasbook_tandauthor|titleasauthor_t%}

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:

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

A more complex example:

{%blocktranswithamount=article.pricecountyears=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'argarg2asthe_url%}{%blocktrans%}
This is a URL: {{the_url}}{%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:

{%blocktranstrimmed%}
First sentence.
Second paragraph.
{%endblocktrans%}

will result in the entry "Firstsentence.Secondparagraph." in the PO file,
compared to "\nFirstsentence.\nSecondsentence.\n", if the trimmed
option had not been specified.

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).

{# Translators: Label of a button that triggers search #}<buttontype="submit">{%trans"Go"%}</button>{# Translators: This is a text of the base template #}{%blocktrans%}Ambiguous translatable block of text{%endblocktrans%}

Note

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

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:

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.

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:

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.

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 standard
gettext interface to access it:

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

There is also an ngettext interface:

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

and even a string interpolation function:

functioninterpolate(fmt,obj,named);

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:

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).

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.

fromdjango.views.decorators.cacheimportcache_pagefromdjango.views.i18nimportjavascript_catalog# The value returned by get_version() must change when translations change.@cache_page(86400,key_prefix='js18n-%s'%get_version())defcached_javascript_catalog(request,domain='djangojs',packages=None):returnjavascript_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.

This function can be used in your root URLconf as a replacement for the normal
django.conf.urls.patterns() function. Django will automatically
prepend the current active language code to all url patterns defined within
i18n_patterns(). Example URL patterns:

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.

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:

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.

...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.pymakemessages 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:

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.

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
"Welcometomysite.", like so:

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

When creating a PO file with your favorite text editor, first edit
the charset line (search for "CHARSET") and set it to the charset
you’ll be using to edit the content. 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 file. 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:

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.pycompilemessages
utility.

You create and update the message files the same way as the other Django message
files – with the django-admin.pymakemessages 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 -ddjangojs parameter, like this:

django-admin.pymakemessages-ddjangojs-lde

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

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:

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

Update the system PATH:

ControlPanel>System>Advanced>EnvironmentVariables.

In the Systemvariables list, click Path, click Edit.

Add ;C:\ProgramFiles\gettext-utils\bin at the end of the
Variablevalue 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”.

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.

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:

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.

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.

Django’s translation machinery uses the standard gettext module that comes
with Python. If you know gettext, you might note these specialties in the
way Django does translation:

The string domain is django or djangojs. This string domain is
used to differentiate between different programs that store their data
in a common message-file library (usually /usr/share/locale/). The
django domain is used for python and template translation strings
and is loaded into the global translation catalogs. The djangojs
domain is only used for JavaScript translation catalogs to make sure
that those are as small as possible.

Django doesn’t use xgettext alone. It uses Python wrappers around
xgettext and msgfmt. This is mostly for convenience.

Once you’ve prepared your translations – or, if you just want to use the
translations that come with Django – you’ll just need to activate translation
for your app.

Behind the scenes, Django has a very flexible model of deciding which language
should be used – installation-wide, for a particular user, or both.

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.

If you want to let each individual user specify which language they
prefer, then you also need to use the LocaleMiddleware.
LocaleMiddleware enables language selection based on data from the request.
It customizes content for each user.

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.

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.

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.

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.

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:

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:

The directories listed in LOCALE_PATHS have the highest
precedence, with the ones appearing first having higher precedence than
the ones appearing later.

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.

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)