2011-10-22 17:17:57 +00:00
|
|
|
===========
|
|
|
|
Translation
|
|
|
|
===========
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
.. module:: django.utils.translation
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
Overview
|
|
|
|
========
|
|
|
|
|
2014-03-12 17:15:36 +00:00
|
|
|
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
|
2011-10-22 17:17:57 +00:00
|
|
|
:term:`translation strings <translation string>`. 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
|
|
|
|
:term:`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
|
|
|
|
:setting:`USE_I18N = False <USE_I18N>` in your settings file. Then Django will
|
|
|
|
make some optimizations so as not to load the internationalization machinery.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
.. note::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
There is also an independent but related :setting:`USE_L10N` setting that
|
|
|
|
controls if Django should implement format localization. See
|
|
|
|
:doc:`/topics/i18n/formatting` for more details.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2012-08-16 20:13:45 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
Make sure you've activated translation for your project (the fastest way is
|
2015-11-07 15:12:37 +00:00
|
|
|
to check if :setting:`MIDDLEWARE` includes
|
2012-08-16 20:13:45 +00:00
|
|
|
:mod:`django.middleware.locale.LocaleMiddleware`). If you haven't yet,
|
|
|
|
see :ref:`how-django-discovers-language-preference`.
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
Internationalization: in Python code
|
|
|
|
====================================
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
Standard translation
|
|
|
|
--------------------
|
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
Specify a translation string by using the function
|
2017-01-26 19:58:33 +00:00
|
|
|
:func:`~django.utils.translation.gettext`. It's convention to import this
|
2011-06-15 10:48:13 +00:00
|
|
|
as a shorter alias, ``_``, to save typing.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2017-01-26 19:56:34 +00:00
|
|
|
.. note::
|
|
|
|
The ``u`` prefixing of ``gettext`` functions was originally to distinguish
|
|
|
|
usage between unicode strings and bytestrings on Python 2. For code that
|
|
|
|
supports only Python 3, they can be used interchangeably. A deprecation for
|
|
|
|
the prefixed functions may happen in a future Django release.
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
.. 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:
|
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. Sometimes, you should use :func:`~django.utils.translation.gettext_lazy`
|
2017-01-20 21:04:05 +00:00
|
|
|
as the default translation method for a particular file. Without ``_()``
|
|
|
|
in the global namespace, the developer has to think about which is the
|
2011-10-14 00:12:01 +00:00
|
|
|
most appropriate translation function.
|
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. The underscore character (``_``) is used to represent "the previous
|
2011-10-14 00:12:01 +00:00
|
|
|
result" in Python's interactive shell and doctest tests. Installing a
|
|
|
|
global ``_()`` function causes interference. Explicitly importing
|
2017-01-26 19:58:33 +00:00
|
|
|
``gettext()`` as ``_()`` avoids this problem.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2016-08-16 07:38:36 +00:00
|
|
|
.. admonition:: What functions may be aliased as ``_``?
|
|
|
|
|
|
|
|
Because of how ``xgettext`` (used by :djadmin:`makemessages`) works, only
|
|
|
|
functions that take a single string argument can be imported as ``_``:
|
|
|
|
|
|
|
|
* :func:`~django.utils.translation.gettext`
|
|
|
|
* :func:`~django.utils.translation.gettext_lazy`
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
In this example, the text ``"Welcome to my site."`` is marked as a translation
|
|
|
|
string::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.http import HttpResponse
|
2018-05-12 17:37:42 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
def my_view(request):
|
|
|
|
output = _("Welcome to my site.")
|
|
|
|
return HttpResponse(output)
|
|
|
|
|
|
|
|
Obviously, you could code this without using the alias. This example is
|
|
|
|
identical to the previous one::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.http import HttpResponse
|
2018-05-12 17:37:42 +00:00
|
|
|
from django.utils.translation import gettext
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
def my_view(request):
|
2017-01-26 19:58:33 +00:00
|
|
|
output = gettext("Welcome to my site.")
|
2010-02-16 12:12:53 +00:00
|
|
|
return HttpResponse(output)
|
|
|
|
|
|
|
|
Translation works on computed values. This example is identical to the previous
|
|
|
|
two::
|
|
|
|
|
|
|
|
def my_view(request):
|
|
|
|
words = ['Welcome', 'to', 'my', 'site.']
|
|
|
|
output = _(' '.join(words))
|
|
|
|
return HttpResponse(output)
|
|
|
|
|
|
|
|
Translation works on variables. Again, here's an identical example::
|
|
|
|
|
|
|
|
def my_view(request):
|
|
|
|
sentence = 'Welcome to my site.'
|
|
|
|
output = _(sentence)
|
|
|
|
return HttpResponse(output)
|
|
|
|
|
|
|
|
(The caveat with using variables or computed values, as in the previous two
|
|
|
|
examples, is that Django's translation-string-detecting utility,
|
2014-07-26 11:21:52 +00:00
|
|
|
:djadmin:`django-admin makemessages <makemessages>`, won't be able to find
|
2011-10-22 17:17:57 +00:00
|
|
|
these strings. More on :djadmin:`makemessages` later.)
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
The strings you pass to ``_()`` or ``gettext()`` can take placeholders,
|
2010-02-16 12:12:53 +00:00
|
|
|
specified with Python's standard named-string interpolation syntax. Example::
|
|
|
|
|
|
|
|
def my_view(request, m, d):
|
2010-11-12 02:48:26 +00:00
|
|
|
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
|
2010-02-16 12:12:53 +00:00
|
|
|
return HttpResponse(output)
|
|
|
|
|
|
|
|
This technique lets language-specific translations reorder the placeholder
|
2010-11-12 02:48:26 +00:00
|
|
|
text. For example, an English translation may be ``"Today is November 26."``,
|
2010-02-16 12:12:53 +00:00
|
|
|
while a Spanish translation may be ``"Hoy es 26 de Noviembre."`` -- with the
|
2014-04-22 23:05:14 +00:00
|
|
|
month and the day placeholders swapped.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
2018-04-18 12:29:21 +00:00
|
|
|
Since string extraction is done by the ``xgettext`` command, only syntaxes
|
2018-09-23 01:12:47 +00:00
|
|
|
supported by ``gettext`` are supported by Django. Python :py:ref:`f-strings
|
|
|
|
<f-strings>` and `JavaScript template strings`_ are not yet supported by
|
|
|
|
``xgettext``.
|
2018-04-18 12:29:21 +00:00
|
|
|
|
|
|
|
.. _JavaScript template strings: https://savannah.gnu.org/bugs/?50920
|
|
|
|
|
2010-11-17 15:37:33 +00:00
|
|
|
.. _translator-comments:
|
|
|
|
|
|
|
|
Comments for translators
|
|
|
|
------------------------
|
|
|
|
|
|
|
|
If you would like to give translators hints about a translatable string, you
|
|
|
|
can add a comment prefixed with the ``Translators`` keyword on the line
|
|
|
|
preceding the string, e.g.::
|
|
|
|
|
|
|
|
def my_view(request):
|
|
|
|
# Translators: This message appears on the home page only
|
2017-01-26 19:58:33 +00:00
|
|
|
output = gettext("Welcome to my site.")
|
2010-11-17 15:37:33 +00:00
|
|
|
|
2013-01-20 18:07:10 +00:00
|
|
|
The comment will then appear in the resulting ``.po`` file associated with the
|
2014-02-16 11:26:56 +00:00
|
|
|
translatable construct located below it and should also be displayed by most
|
2013-01-20 18:07:10 +00:00
|
|
|
translation tools.
|
2010-11-17 15:37:33 +00:00
|
|
|
|
2013-01-20 18:07:10 +00:00
|
|
|
.. note:: Just for completeness, this is the corresponding fragment of the
|
|
|
|
resulting ``.po`` file:
|
|
|
|
|
|
|
|
.. code-block:: po
|
2010-11-17 15:37:33 +00:00
|
|
|
|
2013-01-20 18:07:10 +00:00
|
|
|
#. Translators: This message appears on the home page only
|
|
|
|
# path/to/python/file.py:123
|
|
|
|
msgid "Welcome to my site."
|
|
|
|
msgstr ""
|
2010-11-17 15:37:33 +00:00
|
|
|
|
2013-01-20 18:07:10 +00:00
|
|
|
This also works in templates. See :ref:`translator-comments-in-templates` for
|
|
|
|
more details.
|
2010-11-17 15:37:33 +00:00
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
Marking strings as no-op
|
|
|
|
------------------------
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
Use the function :func:`django.utils.translation.gettext_noop()` to mark a
|
2011-06-15 10:48:13 +00:00
|
|
|
string as a translation string without translating it. The string is later
|
|
|
|
translated from a variable.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
Use this if you have constant strings that should be stored in the source
|
2011-06-15 10:48:13 +00:00
|
|
|
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.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
Pluralization
|
|
|
|
-------------
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
Use the function :func:`django.utils.translation.ngettext()` to specify
|
2011-06-15 10:48:13 +00:00
|
|
|
pluralized messages.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
``ngettext()`` takes three arguments: the singular translation string, the
|
|
|
|
plural translation string and the number of objects.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
This function is useful when you need your Django application to be localizable
|
|
|
|
to languages where the number and complexity of `plural forms
|
2015-11-29 16:29:46 +00:00
|
|
|
<https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
|
2010-02-16 12:12:53 +00:00
|
|
|
greater than the two forms used in English ('object' for the singular and
|
2011-07-10 21:32:39 +00:00
|
|
|
'objects' for all the cases where ``count`` is different from one, irrespective
|
2010-02-16 12:12:53 +00:00
|
|
|
of its value.)
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.http import HttpResponse
|
2018-05-12 17:37:42 +00:00
|
|
|
from django.utils.translation import ngettext
|
2011-06-15 10:48:13 +00:00
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
def hello_world(request, count):
|
2017-01-26 19:58:33 +00:00
|
|
|
page = ngettext(
|
2011-06-15 10:48:13 +00:00
|
|
|
'there is %(count)d object',
|
|
|
|
'there are %(count)d objects',
|
|
|
|
count) % {
|
2010-02-16 12:12:53 +00:00
|
|
|
'count': count,
|
|
|
|
}
|
|
|
|
return HttpResponse(page)
|
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
In this example the number of objects is passed to the translation
|
|
|
|
languages as the ``count`` variable.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2013-12-27 14:57:56 +00:00
|
|
|
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::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import ngettext
|
2013-05-19 10:42:44 +00:00
|
|
|
from myapp.models import Report
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
count = Report.objects.count()
|
|
|
|
if count == 1:
|
|
|
|
name = Report._meta.verbose_name
|
|
|
|
else:
|
|
|
|
name = Report._meta.verbose_name_plural
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
text = ngettext(
|
2013-12-27 14:57:56 +00:00
|
|
|
'There is %(count)d %(name)s available.',
|
|
|
|
'There are %(count)d %(name)s available.',
|
|
|
|
count
|
2010-02-16 12:12:53 +00:00
|
|
|
) % {
|
|
|
|
'count': count,
|
|
|
|
'name': name
|
|
|
|
}
|
|
|
|
|
2018-04-15 21:07:00 +00:00
|
|
|
Don't try to implement your own singular-or-plural logic; it won't be correct.
|
2013-12-27 14:57:56 +00:00
|
|
|
In a case like this, consider something like the following::
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
text = ngettext(
|
2013-12-27 14:57:56 +00:00
|
|
|
'There is %(count)d %(name)s object available.',
|
|
|
|
'There are %(count)d %(name)s objects available.',
|
|
|
|
count
|
|
|
|
) % {
|
|
|
|
'count': count,
|
|
|
|
'name': Report._meta.verbose_name,
|
|
|
|
}
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
.. _pluralization-var-notes:
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
When using ``ngettext()``, make sure you use a single name for every
|
2013-12-27 14:57:56 +00:00
|
|
|
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::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
text = ngettext(
|
2013-12-27 14:57:56 +00:00
|
|
|
'There is %(count)d %(name)s available.',
|
|
|
|
'There are %(count)d %(plural_name)s available.',
|
|
|
|
count
|
|
|
|
) % {
|
|
|
|
'count': Report.objects.count(),
|
2010-11-04 10:48:45 +00:00
|
|
|
'name': Report._meta.verbose_name,
|
2010-02-16 12:12:53 +00:00
|
|
|
'plural_name': Report._meta.verbose_name_plural
|
|
|
|
}
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
You would get an error when running :djadmin:`django-admin
|
2011-10-22 17:17:57 +00:00
|
|
|
compilemessages <compilemessages>`::
|
|
|
|
|
|
|
|
a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-03-20 18:59:10 +00:00
|
|
|
.. 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.
|
|
|
|
|
2010-11-04 10:48:27 +00:00
|
|
|
.. _contextual-markers:
|
|
|
|
|
|
|
|
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
|
2011-06-15 10:48:13 +00:00
|
|
|
:func:`django.utils.translation.pgettext()` function, or the
|
|
|
|
:func:`django.utils.translation.npgettext()` function if the string needs
|
2010-11-04 10:48:27 +00:00
|
|
|
pluralization. Both take a context string as the first variable.
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
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.
|
2010-11-04 10:48:27 +00:00
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
from django.utils.translation import pgettext
|
|
|
|
|
|
|
|
month = pgettext("month name", "May")
|
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
or::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.db import models
|
2011-06-15 10:48:13 +00:00
|
|
|
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'))
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
will appear in the ``.po`` file as:
|
2010-11-04 10:48:27 +00:00
|
|
|
|
|
|
|
.. code-block:: po
|
|
|
|
|
|
|
|
msgctxt "month name"
|
|
|
|
msgid "May"
|
|
|
|
msgstr ""
|
|
|
|
|
2011-10-19 04:59:47 +00:00
|
|
|
Contextual markers are also supported by the :ttag:`trans` and
|
|
|
|
:ttag:`blocktrans` template tags.
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
.. _lazy-translations:
|
|
|
|
|
|
|
|
Lazy translation
|
|
|
|
----------------
|
|
|
|
|
2011-12-15 11:04:57 +00:00
|
|
|
Use the lazy versions of translation functions in
|
|
|
|
:mod:`django.utils.translation` (easily recognizable by the ``lazy`` suffix in
|
|
|
|
their names) to translate strings lazily -- when the value is accessed rather
|
2012-02-17 20:04:11 +00:00
|
|
|
than when they're called.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-12-15 11:04:57 +00:00
|
|
|
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.
|
|
|
|
|
2012-02-17 20:04:11 +00:00
|
|
|
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:
|
2011-12-15 11:04:57 +00:00
|
|
|
|
2012-02-10 01:45:03 +00:00
|
|
|
Model fields and relationships ``verbose_name`` and ``help_text`` option values
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
For example, to translate the help text of the *name* field in the following
|
|
|
|
model, do the following::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.db import models
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
class MyThing(models.Model):
|
2012-08-13 14:54:13 +00:00
|
|
|
name = models.CharField(help_text=_('This is the help text'))
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2014-02-16 11:57:50 +00:00
|
|
|
You can mark names of :class:`~django.db.models.ForeignKey`,
|
|
|
|
:class:`~django.db.models.ManyToManyField` or
|
|
|
|
:class:`~django.db.models.OneToOneField` relationship as translatable by using
|
|
|
|
their :attr:`~django.db.models.Options.verbose_name` options::
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
class MyThing(models.Model):
|
2015-07-22 14:43:21 +00:00
|
|
|
kind = models.ForeignKey(
|
|
|
|
ThingKind,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name='kinds',
|
|
|
|
verbose_name=_('kind'),
|
|
|
|
)
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
Just like you would do in :attr:`~django.db.models.Options.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
|
|
|
|
:attr:`~django.db.models.Options.verbose_name` and
|
|
|
|
:attr:`~django.db.models.Options.verbose_name_plural` options rather than
|
|
|
|
relying on the fallback English-centric and somewhat naïve determination of
|
2013-02-07 22:57:26 +00:00
|
|
|
verbose names Django performs by looking at the model's class name::
|
2011-12-15 11:04:57 +00:00
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.db import models
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
class MyThing(models.Model):
|
2012-08-13 14:54:13 +00:00
|
|
|
name = models.CharField(_('name'), help_text=_('This is the help text'))
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
class Meta:
|
2012-08-13 14:54:13 +00:00
|
|
|
verbose_name = _('my thing')
|
|
|
|
verbose_name_plural = _('my things')
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
Model methods ``short_description`` attribute values
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
For model methods, you can provide translations to Django and the admin site
|
|
|
|
with the ``short_description`` attribute::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.db import models
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
class MyThing(models.Model):
|
2015-07-22 14:43:21 +00:00
|
|
|
kind = models.ForeignKey(
|
|
|
|
ThingKind,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name='kinds',
|
|
|
|
verbose_name=_('kind'),
|
|
|
|
)
|
2011-12-15 11:04:57 +00:00
|
|
|
|
|
|
|
def is_mouse(self):
|
|
|
|
return self.kind.type == MOUSE_TYPE
|
|
|
|
is_mouse.short_description = _('Is it a mouse?')
|
|
|
|
|
2012-02-10 01:45:03 +00:00
|
|
|
Working with lazy translation objects
|
|
|
|
-------------------------------------
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
The result of a ``gettext_lazy()`` call can be used wherever you would use a
|
|
|
|
string (a :class:`str` object) in other Django code, but it may not work with
|
|
|
|
arbitrary Python code. For example, the following won't work because the
|
2018-04-17 22:19:29 +00:00
|
|
|
`requests <https://pypi.org/project/requests/>`_ library doesn't handle
|
2017-01-26 19:58:33 +00:00
|
|
|
``gettext_lazy`` objects::
|
2016-10-25 02:01:13 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
body = gettext_lazy("I \u2764 Django") # (unicode :heart:)
|
2016-10-25 02:01:13 +00:00
|
|
|
requests.post('https://example.com/send', data={'body': body})
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
You can avoid such problems by casting ``gettext_lazy()`` objects to text
|
2016-10-25 02:01:13 +00:00
|
|
|
strings before passing them to non-Django code::
|
|
|
|
|
|
|
|
requests.post('https://example.com/send', data={'body': str(body)})
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
If you don't like the long ``gettext_lazy`` name, you can just alias it as
|
2010-02-16 12:12:53 +00:00
|
|
|
``_`` (underscore), like so::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.db import models
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
class MyThing(models.Model):
|
|
|
|
name = models.CharField(help_text=_('This is the help text'))
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
Using ``gettext_lazy()`` and ``ngettext_lazy()`` to mark strings in models
|
2010-02-16 12:12:53 +00:00
|
|
|
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
|
2012-02-10 01:45:03 +00:00
|
|
|
(so that the correct locale is in effect). This necessitates the use of the
|
|
|
|
helper function described next.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2013-01-30 19:28:16 +00:00
|
|
|
.. _lazy-plural-translations:
|
|
|
|
|
|
|
|
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::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django import forms
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import ngettext_lazy
|
2013-05-19 10:42:44 +00:00
|
|
|
|
2013-01-30 19:28:16 +00:00
|
|
|
class MyForm(forms.Form):
|
2017-01-26 19:58:33 +00:00
|
|
|
error_message = ngettext_lazy("You only provided %(num)d argument",
|
2013-01-30 19:28:16 +00:00
|
|
|
"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):
|
2017-01-26 19:58:33 +00:00
|
|
|
error_message = ngettext_lazy(
|
2016-06-02 19:56:13 +00:00
|
|
|
"You provided %d argument",
|
|
|
|
"You provided %d arguments",
|
|
|
|
)
|
2013-01-30 19:28:16 +00:00
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
# ...
|
|
|
|
if error:
|
|
|
|
raise forms.ValidationError(self.error_message % number)
|
|
|
|
|
|
|
|
|
2016-08-16 10:07:03 +00:00
|
|
|
Formatting strings: ``format_lazy()``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2016-08-16 10:07:03 +00:00
|
|
|
Python's :meth:`str.format()` method will not work when either the
|
|
|
|
``format_string`` or any of the arguments to :meth:`str.format()`
|
|
|
|
contains lazy translation objects. Instead, you can use
|
|
|
|
:func:`django.utils.text.format_lazy()`, which creates a lazy object
|
|
|
|
that runs the ``str.format()`` method only when the result is included
|
|
|
|
in a string. For example::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2016-08-16 10:07:03 +00:00
|
|
|
from django.utils.text import format_lazy
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy
|
2010-02-16 12:12:53 +00:00
|
|
|
...
|
2017-01-26 19:58:33 +00:00
|
|
|
name = gettext_lazy('John Lennon')
|
|
|
|
instrument = gettext_lazy('guitar')
|
2016-08-16 10:07:03 +00:00
|
|
|
result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
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).
|
|
|
|
|
2012-10-18 06:57:21 +00:00
|
|
|
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.functional import lazy
|
|
|
|
from django.utils.safestring import mark_safe
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2012-10-18 06:57:21 +00:00
|
|
|
|
2017-01-18 16:51:29 +00:00
|
|
|
mark_safe_lazy = lazy(mark_safe, str)
|
2012-10-18 06:57:21 +00:00
|
|
|
|
|
|
|
And then later::
|
|
|
|
|
|
|
|
lazy_string = mark_safe_lazy(_("<p>My <strong>string!</strong></p>"))
|
|
|
|
|
2010-12-12 23:02:45 +00:00
|
|
|
Localized names of languages
|
2011-10-22 17:17:57 +00:00
|
|
|
----------------------------
|
2010-12-12 23:02:45 +00:00
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
.. function:: get_language_info
|
|
|
|
|
2010-12-12 23:02:45 +00:00
|
|
|
The ``get_language_info()`` function provides detailed information about
|
|
|
|
languages::
|
|
|
|
|
2016-07-02 16:10:09 +00:00
|
|
|
>>> from django.utils.translation import activate, get_language_info
|
|
|
|
>>> activate('fr')
|
2010-12-12 23:02:45 +00:00
|
|
|
>>> li = get_language_info('de')
|
2016-07-02 16:10:09 +00:00
|
|
|
>>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])
|
|
|
|
German Deutsch Allemand False
|
2010-12-12 23:02:45 +00:00
|
|
|
|
2016-07-02 16:10:09 +00:00
|
|
|
The ``name``, ``name_local``, and ``name_translated`` attributes of the
|
|
|
|
dictionary contain the name of the language in English, in the language
|
|
|
|
itself, and in your current active language respectively. The ``bidi``
|
2010-12-12 23:02:45 +00:00
|
|
|
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.
|
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
.. _specifying-translation-strings-in-template-code:
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
Internationalization: in template code
|
|
|
|
======================================
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
.. highlightlang:: html+django
|
|
|
|
|
2015-01-03 15:10:12 +00:00
|
|
|
Translations in :doc:`Django templates </ref/templates/language>` uses two template
|
2010-02-16 12:12:53 +00:00
|
|
|
tags and a slightly different syntax than in Python code. To give your template
|
|
|
|
access to these tags, put ``{% load i18n %}`` toward the top of your template.
|
2012-08-19 22:46:46 +00:00
|
|
|
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.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-03 08:06:01 +00:00
|
|
|
.. templatetag:: trans
|
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
``trans`` template tag
|
|
|
|
----------------------
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
The ``{% trans %}`` template tag translates either a constant string
|
|
|
|
(enclosed in single or double quotes) or variable content::
|
|
|
|
|
|
|
|
<title>{% trans "This is the title." %}</title>
|
|
|
|
<title>{% trans myvar %}</title>
|
|
|
|
|
|
|
|
If the ``noop`` option is present, variable lookup still takes place but the
|
|
|
|
translation is skipped. This is useful when "stubbing out" content that will
|
|
|
|
require translation in the future::
|
|
|
|
|
|
|
|
<title>{% trans "myvar" noop %}</title>
|
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
Internally, inline translations use an
|
2017-01-26 19:58:33 +00:00
|
|
|
:func:`~django.utils.translation.gettext` call.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
In case a template var (``myvar`` above) is passed to the tag, the tag will
|
|
|
|
first resolve such variable to a string at run-time and then look up that
|
|
|
|
string in the message catalogs.
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
It's not possible to mix a template variable inside a string within ``{% trans
|
|
|
|
%}``. If your translations require strings with variables (placeholders), use
|
2013-12-15 00:50:54 +00:00
|
|
|
:ttag:`{% blocktrans %}<blocktrans>` instead.
|
2010-05-09 13:55:15 +00:00
|
|
|
|
2011-08-30 12:09:45 +00:00
|
|
|
|
|
|
|
If you'd like to retrieve a translated string without displaying it, you can
|
|
|
|
use the following syntax::
|
|
|
|
|
|
|
|
{% trans "This is the title" as the_title %}
|
|
|
|
|
|
|
|
<title>{{ the_title }}</title>
|
|
|
|
<meta name="description" content="{{ the_title }}">
|
|
|
|
|
2015-06-12 12:51:28 +00:00
|
|
|
In practice you'll use this to get a string you can use in multiple places in a
|
|
|
|
template or so you can use the output as an argument for other template tags or
|
|
|
|
filters::
|
2011-08-30 12:09:45 +00:00
|
|
|
|
|
|
|
{% 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 %}
|
2018-01-21 07:09:10 +00:00
|
|
|
{% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br>{% else %}, {% endif %}
|
2011-08-30 12:09:45 +00:00
|
|
|
{% endfor %}
|
|
|
|
</p>
|
|
|
|
|
2011-10-19 04:59:47 +00:00
|
|
|
``{% trans %}`` also supports :ref:`contextual markers<contextual-markers>`
|
|
|
|
using the ``context`` keyword:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
|
|
|
{% trans "May" context "month name" %}
|
|
|
|
|
2011-06-16 16:34:20 +00:00
|
|
|
.. templatetag:: blocktrans
|
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
``blocktrans`` template tag
|
|
|
|
---------------------------
|
|
|
|
|
2011-10-03 08:06:01 +00:00
|
|
|
Contrarily to the :ttag:`trans` tag, the ``blocktrans`` tag allows you to mark
|
2010-05-09 13:55:15 +00:00
|
|
|
complex sentences consisting of literals and variable content for translation
|
|
|
|
by making use of placeholders::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
{% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
|
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
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::
|
|
|
|
|
2010-12-18 02:50:26 +00:00
|
|
|
{% blocktrans with amount=article.price %}
|
2010-05-09 13:55:15 +00:00
|
|
|
That will cost $ {{ amount }}.
|
|
|
|
{% endblocktrans %}
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2010-12-18 02:50:26 +00:00
|
|
|
{% blocktrans with myvar=value|filter %}
|
2010-02-16 12:12:53 +00:00
|
|
|
This will have {{ myvar }} inside.
|
|
|
|
{% endblocktrans %}
|
|
|
|
|
2011-05-23 01:52:49 +00:00
|
|
|
You can use multiple expressions inside a single ``blocktrans`` tag::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-05-23 01:52:49 +00:00
|
|
|
{% blocktrans with book_t=book|title author_t=author|title %}
|
2010-02-16 12:12:53 +00:00
|
|
|
This is {{ book_t }} by {{ author_t }}
|
|
|
|
{% endblocktrans %}
|
|
|
|
|
2011-05-23 01:52:49 +00:00
|
|
|
.. note:: The previous more verbose format is still supported:
|
|
|
|
``{% blocktrans with book|title as book_t and author|title as author_t %}``
|
|
|
|
|
2014-10-13 14:57:01 +00:00
|
|
|
Other block tags (for example ``{% for %}`` or ``{% if %}``) are not allowed
|
|
|
|
inside a ``blocktrans`` tag.
|
|
|
|
|
2018-07-31 15:32:38 +00:00
|
|
|
If resolving one of the block arguments fails, ``blocktrans`` will fall back to
|
2011-09-08 13:24:41 +00:00
|
|
|
the default language by deactivating the currently active language
|
|
|
|
temporarily with the :func:`~django.utils.translation.deactivate_all`
|
|
|
|
function.
|
|
|
|
|
2010-10-08 15:36:15 +00:00
|
|
|
This tag also provides for pluralization. To use it:
|
2010-05-09 13:55:15 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Designate and bind a counter value with the name ``count``. This value will
|
|
|
|
be the one used to select the right plural form.
|
2010-05-09 13:55:15 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Specify both the singular and plural forms separating them with the
|
|
|
|
``{% plural %}`` tag within the ``{% blocktrans %}`` and
|
|
|
|
``{% endblocktrans %}`` tags.
|
2010-05-09 13:55:15 +00:00
|
|
|
|
|
|
|
An example::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2010-12-18 02:50:26 +00:00
|
|
|
{% blocktrans count counter=list|length %}
|
2010-02-16 12:12:53 +00:00
|
|
|
There is only one {{ name }} object.
|
|
|
|
{% plural %}
|
|
|
|
There are {{ counter }} {{ name }} objects.
|
|
|
|
{% endblocktrans %}
|
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
A more complex example::
|
|
|
|
|
2010-12-18 02:50:26 +00:00
|
|
|
{% blocktrans with amount=article.price count years=i.length %}
|
2010-05-09 13:55:15 +00:00
|
|
|
That will cost $ {{ amount }} per year.
|
|
|
|
{% plural %}
|
|
|
|
That will cost $ {{ amount }} per {{ years }} years.
|
|
|
|
{% endblocktrans %}
|
|
|
|
|
2010-12-01 15:06:25 +00:00
|
|
|
When you use both the pluralization feature and bind values to local variables
|
2010-10-08 15:36:15 +00:00
|
|
|
in addition to the counter value, keep in mind that the ``blocktrans``
|
2017-01-26 19:58:33 +00:00
|
|
|
construct is internally converted to an ``ngettext`` call. This means the
|
|
|
|
same :ref:`notes regarding ngettext variables <pluralization-var-notes>`
|
2010-05-09 13:55:15 +00:00
|
|
|
apply.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2010-12-29 14:19:38 +00:00
|
|
|
Reverse URL lookups cannot be carried out within the ``blocktrans`` and should
|
|
|
|
be retrieved (and stored) beforehand::
|
|
|
|
|
2012-07-15 09:19:00 +00:00
|
|
|
{% url 'path.to.view' arg arg2 as the_url %}
|
2010-12-29 14:19:38 +00:00
|
|
|
{% blocktrans %}
|
|
|
|
This is a URL: {{ the_url }}
|
|
|
|
{% endblocktrans %}
|
|
|
|
|
2015-06-12 12:51:28 +00:00
|
|
|
If you'd like to retrieve a translated string without displaying it, you can
|
|
|
|
use the following syntax::
|
|
|
|
|
|
|
|
{% blocktrans asvar the_title %}The title is {{ title }}.{% endblocktrans %}
|
|
|
|
<title>{{ the_title }}</title>
|
|
|
|
<meta name="description" content="{{ the_title }}">
|
|
|
|
|
|
|
|
In practice you'll use this to get a string you can use in multiple places in a
|
|
|
|
template or so you can use the output as an argument for other template tags or
|
|
|
|
filters.
|
|
|
|
|
2011-10-19 04:59:47 +00:00
|
|
|
``{% blocktrans %}`` also supports :ref:`contextual
|
|
|
|
markers<contextual-markers>` using the ``context`` keyword:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
|
|
|
{% blocktrans with name=user.username context "greeting" %}Hi {{ name }}{% endblocktrans %}
|
|
|
|
|
2013-11-02 19:01:17 +00:00
|
|
|
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 ``"\n First sentence.\n Second sentence.\n"``, if the ``trimmed``
|
|
|
|
option had not been specified.
|
|
|
|
|
2013-08-31 11:55:45 +00:00
|
|
|
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).
|
|
|
|
|
2013-01-20 18:07:10 +00:00
|
|
|
.. _translator-comments-in-templates:
|
|
|
|
|
|
|
|
Comments for translators in templates
|
|
|
|
-------------------------------------
|
|
|
|
|
|
|
|
Just like with :ref:`Python code <translator-comments>`, these notes for
|
|
|
|
translators can be specified using comments, either with the :ttag:`comment`
|
|
|
|
tag:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
|
|
|
{% comment %}Translators: View verb{% endcomment %}
|
|
|
|
{% trans "View" %}
|
|
|
|
|
|
|
|
{% comment %}Translators: Short intro blurb{% endcomment %}
|
|
|
|
<p>{% blocktrans %}A multiline translatable
|
|
|
|
literal.{% endblocktrans %}</p>
|
|
|
|
|
|
|
|
or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
2013-05-23 08:19:10 +00:00
|
|
|
{# Translators: Label of a button that triggers search #}
|
2013-01-20 18:07:10 +00:00
|
|
|
<button type="submit">{% trans "Go" %}</button>
|
|
|
|
|
|
|
|
{# Translators: This is a text of the base template #}
|
2013-02-26 20:12:28 +00:00
|
|
|
{% blocktrans %}Ambiguous translatable block of text{% endblocktrans %}
|
2013-01-20 18:07:10 +00:00
|
|
|
|
|
|
|
.. note:: Just for completeness, these are the corresponding fragments of the
|
|
|
|
resulting ``.po`` file:
|
|
|
|
|
|
|
|
.. code-block:: po
|
|
|
|
|
|
|
|
#. 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 ""
|
|
|
|
|
2014-03-13 13:08:11 +00:00
|
|
|
#. Translators: This is a text of the base template
|
2013-01-20 18:07:10 +00:00
|
|
|
# path/to/template/file.html:103
|
|
|
|
msgid "Ambiguous translatable block of text"
|
|
|
|
msgstr ""
|
|
|
|
|
2013-05-18 15:20:02 +00:00
|
|
|
.. templatetag:: language
|
|
|
|
|
|
|
|
Switching language in templates
|
|
|
|
-------------------------------
|
|
|
|
|
|
|
|
If you want to select a language within a template, you can use the
|
|
|
|
``language`` template tag:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
|
|
|
{% 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.
|
|
|
|
|
2018-06-28 14:25:46 +00:00
|
|
|
.. _i18n-template-tags:
|
2010-03-15 12:16:37 +00:00
|
|
|
|
2010-05-09 13:55:15 +00:00
|
|
|
Other tags
|
|
|
|
----------
|
|
|
|
|
2015-01-12 15:48:49 +00:00
|
|
|
These tags also require a ``{% load i18n %}``.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-06-02 19:39:42 +00:00
|
|
|
.. templatetag:: get_available_languages
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-06-02 19:39:42 +00:00
|
|
|
``get_available_languages``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-06-02 19:39:42 +00:00
|
|
|
``{% get_available_languages as LANGUAGES %}`` returns a list of tuples in
|
|
|
|
which the first element is the :term:`language code` and the second is the
|
|
|
|
language name (translated into the currently active locale).
|
|
|
|
|
|
|
|
.. templatetag:: get_current_language
|
|
|
|
|
2015-07-16 10:20:46 +00:00
|
|
|
``get_current_language``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~
|
2015-06-02 19:39:42 +00:00
|
|
|
|
|
|
|
``{% get_current_language as LANGUAGE_CODE %}`` returns the current user's
|
|
|
|
preferred language as a string. Example: ``en-us``. See
|
|
|
|
:ref:`how-django-discovers-language-preference`.
|
|
|
|
|
|
|
|
.. templatetag:: get_current_language_bidi
|
|
|
|
|
|
|
|
``get_current_language_bidi``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
``{% get_current_language_bidi as LANGUAGE_BIDI %}`` returns the current
|
|
|
|
locale's direction. 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.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2018-06-28 14:25:46 +00:00
|
|
|
.. _template-translation-vars:
|
|
|
|
|
|
|
|
``i18n`` context processor
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
If you enable the :class:`django.template.context_processors.i18n` context
|
|
|
|
processor, then each ``RequestContext`` will have access to ``LANGUAGES``,
|
2015-01-12 15:48:49 +00:00
|
|
|
``LANGUAGE_CODE``, and ``LANGUAGE_BIDI`` as defined above.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-06-02 19:39:42 +00:00
|
|
|
.. templatetag:: get_language_info
|
|
|
|
|
|
|
|
``get_language_info``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2010-12-12 23:02:45 +00:00
|
|
|
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::
|
|
|
|
|
2018-01-21 07:09:10 +00:00
|
|
|
Language code: {{ lang.code }}<br>
|
|
|
|
Name of language: {{ lang.name_local }}<br>
|
|
|
|
Name in English: {{ lang.name }}<br>
|
2010-12-12 23:02:45 +00:00
|
|
|
Bi-directional: {{ lang.bidi }}
|
2015-05-31 14:20:19 +00:00
|
|
|
Name in the active language: {{ lang.name_translated }}
|
|
|
|
|
2015-06-02 19:39:42 +00:00
|
|
|
.. templatetag:: get_language_info_list
|
|
|
|
|
|
|
|
``get_language_info_list``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2010-12-12 23:02:45 +00:00
|
|
|
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
|
|
|
|
:setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
|
|
|
|
view <set_language-redirect-view>` for an example of how to display a language
|
|
|
|
selector using ``{% get_language_info_list %}``.
|
|
|
|
|
2015-01-21 16:55:57 +00:00
|
|
|
In addition to :setting:`LANGUAGES` style list of tuples,
|
2010-12-12 23:02:45 +00:00
|
|
|
``{% get_language_info_list %}`` supports simple lists of language codes.
|
|
|
|
If you do this in your view:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
2014-11-22 08:22:38 +00:00
|
|
|
context = {'available_languages': ['en', 'es', 'fr']}
|
|
|
|
return render(request, 'mytemplate.html', context)
|
2010-12-12 23:02:45 +00:00
|
|
|
|
|
|
|
you can iterate over those languages in the template::
|
|
|
|
|
|
|
|
{% get_language_info_list for available_languages as langs %}
|
|
|
|
{% for lang in langs %} ... {% endfor %}
|
|
|
|
|
2015-06-02 19:39:42 +00:00
|
|
|
.. templatefilter:: language_name
|
|
|
|
.. templatefilter:: language_name_local
|
|
|
|
.. templatefilter:: language_bidi
|
2015-05-31 14:20:19 +00:00
|
|
|
.. templatefilter:: language_name_translated
|
2015-06-02 19:39:42 +00:00
|
|
|
|
|
|
|
Template filters
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
2010-12-12 23:02:45 +00:00
|
|
|
There are also simple filters available for convenience:
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* ``{{ LANGUAGE_CODE|language_name }}`` ("German")
|
|
|
|
* ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
|
2014-12-11 15:19:10 +00:00
|
|
|
* ``{{ LANGUAGE_CODE|language_bidi }}`` (False)
|
2015-05-31 14:20:19 +00:00
|
|
|
* ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active language is Czech)
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
Internationalization: in JavaScript code
|
|
|
|
========================================
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-02-07 18:48:40 +00:00
|
|
|
.. highlightlang:: python
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
Adding translations to JavaScript poses some problems:
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* JavaScript code doesn't have access to a ``gettext`` implementation.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
* JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to
|
|
|
|
be delivered by the server.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* The translation catalogs for JavaScript should be kept as small as
|
|
|
|
possible.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
Django provides an integrated solution for these problems: It passes the
|
|
|
|
translations into JavaScript, so you can call ``gettext``, etc., from within
|
|
|
|
JavaScript.
|
|
|
|
|
2016-03-07 20:52:08 +00:00
|
|
|
The main solution to these problems is the following ``JavaScriptCatalog`` view,
|
|
|
|
which generates a JavaScript code library with functions that mimic the
|
|
|
|
``gettext`` interface, plus an array of translation strings.
|
|
|
|
|
|
|
|
The ``JavaScriptCatalog`` view
|
|
|
|
------------------------------
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2010-05-09 04:25:34 +00:00
|
|
|
.. module:: django.views.i18n
|
|
|
|
|
2016-03-07 20:52:08 +00:00
|
|
|
.. class:: JavaScriptCatalog
|
|
|
|
|
|
|
|
A view that produces a JavaScript code library with functions that mimic
|
|
|
|
the ``gettext`` interface, plus an array of translation strings.
|
|
|
|
|
|
|
|
**Attributes**
|
|
|
|
|
|
|
|
.. attribute:: domain
|
|
|
|
|
|
|
|
Translation domain containing strings to add in the view output.
|
|
|
|
Defaults to ``'djangojs'``.
|
|
|
|
|
|
|
|
.. attribute:: packages
|
|
|
|
|
|
|
|
A list of :attr:`application names <django.apps.AppConfig.name>` among
|
|
|
|
installed applications. Those apps should contain a ``locale``
|
|
|
|
directory. All those catalogs plus all catalogs found in
|
|
|
|
:setting:`LOCALE_PATHS` (which are always included) are merged into one
|
|
|
|
catalog. Defaults to ``None``, which means that all available
|
|
|
|
translations from all :setting:`INSTALLED_APPS` are provided in the
|
|
|
|
JavaScript output.
|
|
|
|
|
|
|
|
**Example with default values**::
|
|
|
|
|
|
|
|
from django.views.i18n import JavaScriptCatalog
|
|
|
|
|
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
|
2016-03-07 20:52:08 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
**Example with custom packages**::
|
|
|
|
|
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('jsi18n/myapp/',
|
|
|
|
JavaScriptCatalog.as_view(packages=['your.app.label']),
|
|
|
|
name='javascript-catalog'),
|
2016-03-07 20:52:08 +00:00
|
|
|
]
|
|
|
|
|
2016-10-07 11:00:39 +00:00
|
|
|
If your root URLconf uses :func:`~django.conf.urls.i18n.i18n_patterns`,
|
|
|
|
``JavaScriptCatalog`` must also be wrapped by ``i18n_patterns()`` for the
|
|
|
|
catalog to be correctly generated.
|
|
|
|
|
|
|
|
**Example with** ``i18n_patterns()``::
|
|
|
|
|
|
|
|
from django.conf.urls.i18n import i18n_patterns
|
|
|
|
|
|
|
|
urlpatterns = i18n_patterns(
|
2016-10-20 17:29:04 +00:00
|
|
|
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
|
2016-10-07 11:00:39 +00:00
|
|
|
)
|
|
|
|
|
2016-03-07 20:52:08 +00:00
|
|
|
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.
|
|
|
|
|
|
|
|
If you use more than one ``JavaScriptCatalog`` view on a site and some of them
|
|
|
|
define the same strings, the strings in the catalog that was loaded last take
|
|
|
|
precedence.
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
Using the JavaScript translation catalog
|
|
|
|
----------------------------------------
|
|
|
|
|
2011-02-07 18:48:40 +00:00
|
|
|
.. highlightlang:: javascript
|
|
|
|
|
|
|
|
To use the catalog, just pull in the dynamically generated script like this:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2016-01-27 10:32:06 +00:00
|
|
|
<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
This uses reverse URL lookup to find the URL of the JavaScript catalog view.
|
2015-04-14 16:19:20 +00:00
|
|
|
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::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
document.write(gettext('this is to be translated'));
|
|
|
|
|
2015-04-14 16:19:20 +00:00
|
|
|
``ngettext``
|
|
|
|
~~~~~~~~~~~~
|
|
|
|
|
|
|
|
The ``ngettext`` function provides an interface to pluralize words and
|
|
|
|
phrases::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-04-29 15:21:57 +00:00
|
|
|
var object_count = 1 // or 0, or 2, or 3, ...
|
2010-02-16 12:12:53 +00:00
|
|
|
s = ngettext('literal for the singular case',
|
2015-04-29 15:21:57 +00:00
|
|
|
'literal for the plural case', object_count);
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-04-14 16:19:20 +00:00
|
|
|
``interpolate``
|
|
|
|
~~~~~~~~~~~~~~~
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2015-04-14 16:19:20 +00:00
|
|
|
The ``interpolate`` function supports dynamically populating a format string.
|
2010-02-16 12:12:53 +00:00
|
|
|
The interpolation syntax is borrowed from Python, so the ``interpolate``
|
|
|
|
function supports both positional and named interpolation:
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* 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::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
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'
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Named interpolation: This mode is selected by passing the optional
|
2015-04-14 16:19:20 +00:00
|
|
|
boolean ``named`` parameter as ``true``. ``obj`` contains a JavaScript
|
2011-10-14 00:12:01 +00:00
|
|
|
object or associative array. For example::
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
d = {
|
|
|
|
count: 10,
|
|
|
|
total: 50
|
|
|
|
};
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
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);
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
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).
|
|
|
|
|
2015-04-14 16:19:20 +00:00
|
|
|
``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:
|
|
|
|
|
|
|
|
* :setting:`DATE_FORMAT`
|
|
|
|
* :setting:`DATE_INPUT_FORMATS`
|
|
|
|
* :setting:`DATETIME_FORMAT`
|
|
|
|
* :setting:`DATETIME_INPUT_FORMATS`
|
|
|
|
* :setting:`DECIMAL_SEPARATOR`
|
|
|
|
* :setting:`FIRST_DAY_OF_WEEK`
|
|
|
|
* :setting:`MONTH_DAY_FORMAT`
|
|
|
|
* :setting:`NUMBER_GROUPING`
|
|
|
|
* :setting:`SHORT_DATE_FORMAT`
|
|
|
|
* :setting:`SHORT_DATETIME_FORMAT`
|
|
|
|
* :setting:`THOUSAND_SEPARATOR`
|
|
|
|
* :setting:`TIME_FORMAT`
|
|
|
|
* :setting:`TIME_INPUT_FORMATS`
|
|
|
|
* :setting:`YEAR_MONTH_FORMAT`
|
|
|
|
|
|
|
|
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
|
|
|
|
(:func:`~django.utils.translation.pgettext()`), providing a contextually
|
|
|
|
translated word::
|
|
|
|
|
|
|
|
document.write(pgettext('month name', 'May'));
|
|
|
|
|
|
|
|
``npgettext``
|
|
|
|
~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
The ``npgettext`` function also behaves like the Python variant
|
|
|
|
(:func:`~django.utils.translation.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 :tfilter:`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.
|
|
|
|
|
2016-01-25 16:57:14 +00:00
|
|
|
.. highlight:: python
|
|
|
|
|
2016-03-07 20:52:08 +00:00
|
|
|
The ``JSONCatalog`` view
|
|
|
|
------------------------
|
|
|
|
|
|
|
|
.. class:: JSONCatalog
|
|
|
|
|
|
|
|
In order to use another client-side library to handle translations, you may
|
|
|
|
want to take advantage of the ``JSONCatalog`` view. It's similar to
|
|
|
|
:class:`~django.views.i18n.JavaScriptCatalog` but returns a JSON response.
|
|
|
|
|
|
|
|
See the documentation for :class:`~django.views.i18n.JavaScriptCatalog`
|
|
|
|
to learn about possible values and use of the ``domain`` and ``packages``
|
|
|
|
attributes.
|
|
|
|
|
|
|
|
The response format is as follows:
|
|
|
|
|
|
|
|
.. code-block:: text
|
|
|
|
|
|
|
|
{
|
|
|
|
"catalog": {
|
|
|
|
# Translations catalog
|
|
|
|
},
|
|
|
|
"formats": {
|
|
|
|
# Language formats for date, time, etc.
|
|
|
|
},
|
|
|
|
"plural": "..." # Expression for plural forms, or null.
|
|
|
|
}
|
|
|
|
|
|
|
|
.. JSON doesn't allow comments so highlighting as JSON won't work here.
|
|
|
|
|
2013-02-25 21:29:38 +00:00
|
|
|
Note on performance
|
|
|
|
-------------------
|
|
|
|
|
2016-03-07 20:52:08 +00:00
|
|
|
The various JavaScript/JSON i18n views generate 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.
|
2013-02-25 21:29:38 +00:00
|
|
|
|
|
|
|
Server-side caching will reduce CPU load. It's easily implemented with the
|
|
|
|
:func:`~django.views.decorators.cache.cache_page` decorator. To trigger cache
|
2013-11-02 01:29:39 +00:00
|
|
|
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
|
2016-01-25 16:57:14 +00:00
|
|
|
URL::
|
2013-02-25 21:29:38 +00:00
|
|
|
|
|
|
|
from django.views.decorators.cache import cache_page
|
2016-03-07 20:52:08 +00:00
|
|
|
from django.views.i18n import JavaScriptCatalog
|
2013-02-25 21:29:38 +00:00
|
|
|
|
|
|
|
# The value returned by get_version() must change when translations change.
|
2016-03-07 20:52:08 +00:00
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('jsi18n/',
|
|
|
|
cache_page(86400, key_prefix='js18n-%s' % get_version())(JavaScriptCatalog.as_view()),
|
|
|
|
name='javascript-catalog'),
|
2016-03-07 20:52:08 +00:00
|
|
|
]
|
2013-02-25 21:29:38 +00:00
|
|
|
|
|
|
|
Client-side caching will save bandwidth and make your site load faster. If
|
2016-04-03 10:15:10 +00:00
|
|
|
you're using ETags (:class:`~django.middleware.http.ConditionalGetMiddleware`),
|
|
|
|
you're already covered. Otherwise, you can apply :ref:`conditional decorators
|
2013-02-25 21:29:38 +00:00
|
|
|
<conditional-decorators>`. In the following example, the cache is invalidated
|
2016-01-25 16:57:14 +00:00
|
|
|
whenever you restart your application server::
|
2013-02-25 21:29:38 +00:00
|
|
|
|
|
|
|
from django.utils import timezone
|
|
|
|
from django.views.decorators.http import last_modified
|
2016-03-07 20:52:08 +00:00
|
|
|
from django.views.i18n import JavaScriptCatalog
|
2013-02-25 21:29:38 +00:00
|
|
|
|
|
|
|
last_modified_date = timezone.now()
|
2014-08-18 14:30:44 +00:00
|
|
|
|
2016-03-07 20:52:08 +00:00
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('jsi18n/',
|
|
|
|
last_modified(lambda req, **kw: last_modified_date)(JavaScriptCatalog.as_view()),
|
|
|
|
name='javascript-catalog'),
|
2016-03-07 20:52:08 +00:00
|
|
|
]
|
2013-02-25 21:29:38 +00:00
|
|
|
|
2015-04-30 19:39:29 +00:00
|
|
|
You can even pre-generate the JavaScript catalog as part of your deployment
|
2013-02-25 21:29:38 +00:00
|
|
|
procedure and serve it as a static file. This radical technique is implemented
|
|
|
|
in django-statici18n_.
|
|
|
|
|
2016-04-28 14:09:57 +00:00
|
|
|
.. _django-statici18n: https://django-statici18n.readthedocs.io/en/latest/
|
2013-02-25 21:29:38 +00:00
|
|
|
|
2011-06-15 17:29:10 +00:00
|
|
|
.. _url-internationalization:
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
Internationalization: in URL patterns
|
|
|
|
=====================================
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
.. module:: django.conf.urls.i18n
|
|
|
|
|
|
|
|
Django provides two mechanisms to internationalize URL patterns:
|
|
|
|
|
|
|
|
* Adding the language prefix to the root of the URL patterns to make it
|
|
|
|
possible for :class:`~django.middleware.locale.LocaleMiddleware` to detect
|
|
|
|
the language to activate from the requested URL.
|
|
|
|
|
|
|
|
* Making URL patterns themselves translatable via the
|
2017-01-26 19:58:33 +00:00
|
|
|
:func:`django.utils.translation.gettext_lazy()` function.
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
Using either one of these features requires that an active language be set
|
|
|
|
for each request; in other words, you need to have
|
|
|
|
:class:`django.middleware.locale.LocaleMiddleware` in your
|
2015-11-07 15:12:37 +00:00
|
|
|
:setting:`MIDDLEWARE` setting.
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
Language prefix in URL patterns
|
|
|
|
-------------------------------
|
|
|
|
|
2016-02-29 08:24:19 +00:00
|
|
|
.. function:: i18n_patterns(*urls, prefix_default_language=True)
|
2014-04-02 00:46:34 +00:00
|
|
|
|
2015-12-14 17:36:09 +00:00
|
|
|
This function can be used in a root URLconf and Django will automatically
|
2016-07-06 19:31:12 +00:00
|
|
|
prepend the current active language code to all URL patterns defined within
|
2016-02-29 08:24:19 +00:00
|
|
|
:func:`~django.conf.urls.i18n.i18n_patterns`.
|
|
|
|
|
|
|
|
Setting ``prefix_default_language`` to ``False`` removes the prefix from the
|
|
|
|
default language (:setting:`LANGUAGE_CODE`). This can be useful when adding
|
|
|
|
translations to existing site so that the current URLs won't change.
|
|
|
|
|
|
|
|
Example URL patterns::
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
from django.conf.urls.i18n import i18n_patterns
|
2018-11-23 09:11:51 +00:00
|
|
|
from django.urls import include, path
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2014-08-12 14:54:42 +00:00
|
|
|
from about import views as about_views
|
|
|
|
from news import views as news_views
|
2014-08-12 18:40:32 +00:00
|
|
|
from sitemap.views import sitemap
|
2014-08-12 14:54:42 +00:00
|
|
|
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('sitemap.xml', sitemap, name='sitemap-xml'),
|
2014-04-02 00:46:34 +00:00
|
|
|
]
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2015-05-28 15:25:52 +00:00
|
|
|
news_patterns = ([
|
2016-10-20 17:29:04 +00:00
|
|
|
path('', news_views.index, name='index'),
|
2017-09-25 17:06:11 +00:00
|
|
|
path('category/<slug:slug>/', news_views.category, name='category'),
|
|
|
|
path('<slug:slug>/', news_views.details, name='detail'),
|
2015-05-28 15:25:52 +00:00
|
|
|
], 'news')
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns += i18n_patterns(
|
2016-10-20 17:29:04 +00:00
|
|
|
path('about/', about_views.main, name='about'),
|
|
|
|
path('news/', include(news_patterns, namespace='news')),
|
2011-06-15 17:29:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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::
|
|
|
|
|
2016-01-25 16:57:14 +00:00
|
|
|
>>> from django.urls import reverse
|
|
|
|
>>> from django.utils.translation import activate
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
>>> activate('en')
|
2015-11-07 14:50:43 +00:00
|
|
|
>>> reverse('sitemap-xml')
|
2011-06-15 17:29:10 +00:00
|
|
|
'/sitemap.xml'
|
|
|
|
>>> reverse('news:index')
|
|
|
|
'/en/news/'
|
|
|
|
|
|
|
|
>>> activate('nl')
|
|
|
|
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
|
|
|
|
'/nl/news/news-slug/'
|
|
|
|
|
2016-02-29 08:24:19 +00:00
|
|
|
With ``prefix_default_language=False`` and ``LANGUAGE_CODE='en'``, the URLs
|
|
|
|
will be::
|
|
|
|
|
|
|
|
>>> activate('en')
|
|
|
|
>>> reverse('news:index')
|
|
|
|
'/news/'
|
|
|
|
|
|
|
|
>>> activate('nl')
|
|
|
|
>>> reverse('news:index')
|
|
|
|
'/nl/news/'
|
|
|
|
|
2011-06-15 17:29:10 +00:00
|
|
|
.. warning::
|
|
|
|
|
2015-12-14 17:36:09 +00:00
|
|
|
:func:`~django.conf.urls.i18n.i18n_patterns` is only allowed in a root
|
2011-06-15 17:29:10 +00:00
|
|
|
URLconf. Using it within an included URLconf will throw an
|
2012-12-25 14:56:22 +00:00
|
|
|
:exc:`~django.core.exceptions.ImproperlyConfigured` exception.
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
Ensure that you don't have non-prefixed URL patterns that might collide
|
|
|
|
with an automatically-added language prefix.
|
|
|
|
|
2016-12-23 00:16:26 +00:00
|
|
|
.. _translating-urlpatterns:
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
Translating URL patterns
|
|
|
|
------------------------
|
|
|
|
|
|
|
|
URL patterns can also be marked translatable using the
|
2017-01-26 19:58:33 +00:00
|
|
|
:func:`~django.utils.translation.gettext_lazy` function. Example::
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
from django.conf.urls.i18n import i18n_patterns
|
2016-10-20 17:29:04 +00:00
|
|
|
from django.urls import include, path
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2014-08-12 14:54:42 +00:00
|
|
|
from about import views as about_views
|
|
|
|
from news import views as news_views
|
|
|
|
from sitemaps.views import sitemap
|
|
|
|
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns = [
|
2016-10-20 17:29:04 +00:00
|
|
|
path('sitemap.xml', sitemap, name='sitemap-xml'),
|
2014-04-02 00:46:34 +00:00
|
|
|
]
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2015-05-28 15:25:52 +00:00
|
|
|
news_patterns = ([
|
2016-10-20 17:29:04 +00:00
|
|
|
path('', news_views.index, name='index'),
|
2017-09-25 17:06:11 +00:00
|
|
|
path(_('category/<slug:slug>/'), news_views.category, name='category'),
|
|
|
|
path('<slug:slug>/', news_views.details, name='detail'),
|
2015-05-28 15:25:52 +00:00
|
|
|
], 'news')
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2014-04-02 00:46:34 +00:00
|
|
|
urlpatterns += i18n_patterns(
|
2016-10-20 17:29:04 +00:00
|
|
|
path(_('about/'), about_views.main, name='about'),
|
|
|
|
path(_('news/'), include(news_patterns, namespace='news')),
|
2011-06-15 17:29:10 +00:00
|
|
|
)
|
|
|
|
|
2015-12-30 15:51:16 +00:00
|
|
|
After you've created the translations, the :func:`~django.urls.reverse`
|
|
|
|
function will return the URL in the active language. Example::
|
2011-06-15 17:29:10 +00:00
|
|
|
|
2016-01-25 16:57:14 +00:00
|
|
|
>>> from django.urls import reverse
|
|
|
|
>>> from django.utils.translation import activate
|
2011-06-15 17:29:10 +00:00
|
|
|
|
|
|
|
>>> 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::
|
|
|
|
|
2018-02-21 14:30:56 +00:00
|
|
|
In most cases, it's best to use translated URLs only within a language code
|
|
|
|
prefixed block of patterns (using
|
2011-06-15 17:29:10 +00:00
|
|
|
:func:`~django.conf.urls.i18n.i18n_patterns`), to avoid the possibility
|
|
|
|
that a carelessly translated URL causes a collision with a non-translated
|
|
|
|
URL pattern.
|
|
|
|
|
2011-07-04 09:52:06 +00:00
|
|
|
.. _reversing_in_templates:
|
|
|
|
|
|
|
|
Reversing in templates
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
If localized URLs get reversed in templates they always use the current
|
2013-05-18 15:20:02 +00:00
|
|
|
language. To link to a URL in another language use the :ttag:`language`
|
2011-07-04 09:52:06 +00:00
|
|
|
template tag. It enables the given language in the enclosed template section:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
|
|
|
{% load i18n %}
|
|
|
|
|
|
|
|
{% get_available_languages as languages %}
|
|
|
|
|
|
|
|
{% trans "View this category in:" %}
|
|
|
|
{% for lang_code, lang_name in languages %}
|
|
|
|
{% language lang_code %}
|
2012-07-15 09:19:00 +00:00
|
|
|
<a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
|
2011-07-04 09:52:06 +00:00
|
|
|
{% endlanguage %}
|
|
|
|
{% endfor %}
|
|
|
|
|
|
|
|
The :ttag:`language` tag expects the language code as the only argument.
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
.. _how-to-create-language-files:
|
|
|
|
|
|
|
|
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 :term:`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.
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
Django comes with a tool, :djadmin:`django-admin makemessages
|
2011-10-22 17:17:57 +00:00
|
|
|
<makemessages>`, that automates the creation and upkeep of these files.
|
|
|
|
|
|
|
|
.. admonition:: 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::
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
django-admin makemessages -l de
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2014-08-24 03:01:13 +00:00
|
|
|
...where ``de`` is the :term:`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.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
The script should be run from one of two places:
|
|
|
|
|
2013-07-07 01:24:38 +00:00
|
|
|
* The root directory of your Django project (the one that contains
|
|
|
|
``manage.py``).
|
|
|
|
* The root directory of one of your Django apps.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
The script runs over your project source tree or your application source tree
|
2013-07-04 09:44:22 +00:00
|
|
|
and pulls out all strings marked for translation (see
|
|
|
|
:ref:`how-django-discovers-translations` and be sure :setting:`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``.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2015-01-26 20:39:52 +00:00
|
|
|
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 :setting:`LOCALE_PATHS` or
|
|
|
|
will generate an error if :setting:`LOCALE_PATHS` is empty.
|
2013-11-30 09:53:08 +00:00
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
By default :djadmin:`django-admin makemessages <makemessages>` examines every
|
2017-08-11 19:22:10 +00:00
|
|
|
file that has the ``.html``, ``.txt`` or ``.py`` file extension. If you want to
|
|
|
|
override that default, use the :option:`--extension <makemessages --extension>`
|
|
|
|
or ``-e`` option to specify the file extensions to examine::
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
django-admin makemessages -l de -e txt
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
|
|
|
|
multiple times::
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
django-admin makemessages -l de -e html,txt -e xml
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
When :ref:`creating message files from JavaScript source code
|
|
|
|
<creating-message-files-from-js-code>` you need to use the special
|
2018-07-31 15:32:38 +00:00
|
|
|
``djangojs`` domain, **not** ``-e js``.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2015-04-01 20:36:51 +00:00
|
|
|
.. admonition:: Using Jinja2 templates?
|
|
|
|
|
|
|
|
:djadmin:`makemessages` doesn't understand the syntax of Jinja2 templates.
|
2015-09-21 23:09:27 +00:00
|
|
|
To extract strings from a project containing Jinja2 templates, use `Message
|
|
|
|
Extracting`_ from Babel_ instead.
|
2015-04-01 20:36:51 +00:00
|
|
|
|
|
|
|
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 :djadmin:`makemessages`, can replace it
|
|
|
|
in general, and doesn't depend on ``gettext``. For more information, read
|
|
|
|
its documentation about `working with message catalogs`_.
|
|
|
|
|
2016-06-16 01:20:23 +00:00
|
|
|
.. _Message extracting: http://babel.pocoo.org/en/latest/messages.html#message-extraction
|
2015-04-01 20:36:51 +00:00
|
|
|
.. _Babel: http://babel.pocoo.org/
|
2016-06-16 01:20:23 +00:00
|
|
|
.. _working with message catalogs: http://babel.pocoo.org/en/latest/messages.html
|
2015-04-01 20:36:51 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
.. admonition:: No gettext?
|
|
|
|
|
|
|
|
If you don't have the ``gettext`` utilities installed,
|
|
|
|
:djadmin:`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.
|
|
|
|
|
|
|
|
.. admonition:: Working on Windows?
|
|
|
|
|
|
|
|
If you're using Windows and need to install the GNU gettext utilities so
|
|
|
|
:djadmin:`makemessages` works, see :ref:`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.")
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
...then :djadmin:`django-admin makemessages <makemessages>` will have created
|
2014-08-19 00:37:16 +00:00
|
|
|
a ``.po`` file containing the following snippet -- a message:
|
|
|
|
|
|
|
|
.. code-block:: po
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
#: 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!
|
|
|
|
|
|
|
|
.. admonition:: Mind your charset
|
|
|
|
|
2015-02-03 12:43:51 +00:00
|
|
|
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
|
2011-10-22 17:17:57 +00:00
|
|
|
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::
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
django-admin makemessages -a
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
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
|
2014-07-26 11:21:52 +00:00
|
|
|
this with the :djadmin:`django-admin compilemessages <compilemessages>`
|
2011-10-22 17:17:57 +00:00
|
|
|
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
|
2014-07-26 11:21:52 +00:00
|
|
|
which you ran :djadmin:`django-admin makemessages <makemessages>`, run
|
|
|
|
:djadmin:`django-admin compilemessages <compilemessages>` like this::
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
django-admin compilemessages
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
That's it. Your translations are ready for use.
|
|
|
|
|
|
|
|
.. admonition:: Working on Windows?
|
|
|
|
|
|
|
|
If you're using Windows and need to install the GNU gettext utilities so
|
2014-07-26 11:21:52 +00:00
|
|
|
:djadmin:`django-admin compilemessages <compilemessages>` works see
|
2011-10-22 17:17:57 +00:00
|
|
|
:ref:`gettext_on_windows` for more information.
|
|
|
|
|
|
|
|
.. admonition:: .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.
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
Troubleshooting: ``gettext()`` incorrectly detects ``python-format`` in strings with percent signs
|
2017-03-20 22:30:32 +00:00
|
|
|
--------------------------------------------------------------------------------------------------
|
2016-11-10 03:22:56 +00:00
|
|
|
|
|
|
|
In some cases, such as strings with a percent sign followed by a space and a
|
|
|
|
:ref:`string conversion type <old-string-formatting>` (e.g.
|
2017-01-26 19:58:33 +00:00
|
|
|
``_("10% interest")``), :func:`~django.utils.translation.gettext` incorrectly
|
2016-11-10 03:22:56 +00:00
|
|
|
flags strings with ``python-format``.
|
|
|
|
|
|
|
|
If you try to compile message files with incorrectly flagged strings, you'll
|
|
|
|
get an error message like ``number of format specifications in 'msgid' and
|
|
|
|
'msgstr' does not match`` or ``'msgstr' is not a valid Python format string,
|
|
|
|
unlike 'msgid'``.
|
|
|
|
|
|
|
|
To workaround this, you can escape percent signs by adding a second percent
|
|
|
|
sign::
|
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2018-01-17 07:47:37 +00:00
|
|
|
output = _("10%% interest")
|
2016-11-10 03:22:56 +00:00
|
|
|
|
|
|
|
Or you can use ``no-python-format`` so that all percent signs are treated as
|
|
|
|
literals::
|
|
|
|
|
|
|
|
# xgettext:no-python-format
|
2018-01-17 07:47:37 +00:00
|
|
|
output = _("10% interest")
|
2016-11-10 03:22:56 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
.. _creating-message-files-from-js-code:
|
|
|
|
|
|
|
|
Creating message files from JavaScript source code
|
|
|
|
--------------------------------------------------
|
|
|
|
|
|
|
|
You create and update the message files the same way as the other Django message
|
2014-07-26 11:21:52 +00:00
|
|
|
files -- with the :djadmin:`django-admin makemessages <makemessages>` tool.
|
2011-10-22 17:17:57 +00:00
|
|
|
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::
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
django-admin makemessages -d djangojs -l de
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
This would create or update the message file for JavaScript for German. After
|
2014-07-26 11:21:52 +00:00
|
|
|
updating message files, just run :djadmin:`django-admin compilemessages
|
2011-10-22 17:17:57 +00:00
|
|
|
<compilemessages>` the same way as you do with normal Django message files.
|
|
|
|
|
|
|
|
.. _gettext_on_windows:
|
|
|
|
|
|
|
|
``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
|
2016-02-06 14:51:06 +00:00
|
|
|
test or compile a changed message file, download `a precompiled binary
|
2018-01-07 13:28:41 +00:00
|
|
|
installer <https://mlocati.github.io/articles/gettext-iconv-windows.html>`_.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
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".
|
|
|
|
|
2014-10-29 14:38:46 +00:00
|
|
|
.. _customizing-makemessages:
|
|
|
|
|
|
|
|
Customizing the ``makemessages`` command
|
|
|
|
----------------------------------------
|
|
|
|
|
|
|
|
If you want to pass additional parameters to ``xgettext``, you need to create a
|
|
|
|
custom :djadmin:`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
|
|
|
|
:djadmin:`makemessages` command::
|
|
|
|
|
|
|
|
from django.core.management.commands import makemessages
|
|
|
|
|
|
|
|
class Command(makemessages.Command):
|
|
|
|
|
|
|
|
def add_arguments(self, parser):
|
2017-01-22 06:57:14 +00:00
|
|
|
super().add_arguments(parser)
|
2016-06-02 19:56:13 +00:00
|
|
|
parser.add_argument(
|
|
|
|
'--extra-keyword',
|
|
|
|
dest='xgettext_keywords',
|
|
|
|
action='append',
|
|
|
|
)
|
2014-10-29 14:38:46 +00:00
|
|
|
|
|
|
|
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]
|
|
|
|
)
|
2017-01-22 06:57:14 +00:00
|
|
|
super().handle(*args, **options)
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
Miscellaneous
|
|
|
|
=============
|
|
|
|
|
2010-12-12 23:02:45 +00:00
|
|
|
.. _set_language-redirect-view:
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
The ``set_language`` redirect view
|
2011-10-22 17:17:57 +00:00
|
|
|
----------------------------------
|
2010-02-16 12:12:53 +00:00
|
|
|
|
2012-12-29 15:35:12 +00:00
|
|
|
.. currentmodule:: django.views.i18n
|
|
|
|
|
2010-05-09 04:25:34 +00:00
|
|
|
.. function:: set_language(request)
|
|
|
|
|
2011-06-15 10:48:13 +00:00
|
|
|
As a convenience, Django comes with a view, :func:`django.views.i18n.set_language`,
|
2012-02-19 09:19:38 +00:00
|
|
|
that sets a user's language preference and redirects to a given URL or, by default,
|
|
|
|
back to the previous page.
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
Activate this view by adding the following line to your URLconf::
|
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
path('i18n/', include('django.conf.urls.i18n')),
|
2010-02-16 12:12:53 +00:00
|
|
|
|
|
|
|
(Note that this example makes the view available at ``/i18n/setlang/``.)
|
|
|
|
|
2012-08-02 10:45:55 +00:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
Make sure that you don't include the above URL within
|
|
|
|
:func:`~django.conf.urls.i18n.i18n_patterns` - it needs to be
|
|
|
|
language-independent itself to work correctly.
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
The view expects to be called via the ``POST`` method, with a ``language``
|
2017-12-02 12:00:30 +00:00
|
|
|
parameter set in request. If session support is enabled, the view saves the
|
|
|
|
language choice in the user's session. It also saves the language choice in a
|
|
|
|
cookie that is named ``django_language`` by default. (The name can be changed
|
|
|
|
through the :setting:`LANGUAGE_COOKIE_NAME` setting.)
|
|
|
|
|
2016-03-28 17:23:04 +00:00
|
|
|
After setting the language choice, Django looks for a ``next`` parameter in the
|
|
|
|
``POST`` or ``GET`` data. If that is found and Django considers it to be a safe
|
|
|
|
URL (i.e. it doesn't point to a different host and uses a safe scheme), a
|
|
|
|
redirect to that URL will be performed. Otherwise, Django may fall back to
|
|
|
|
redirecting the user to the URL from the ``Referer`` header or, if it is not
|
|
|
|
set, to ``/``, depending on the nature of the request:
|
|
|
|
|
|
|
|
* For AJAX requests, the fallback will be performed only if the ``next``
|
|
|
|
parameter was set. Otherwise a 204 status code (No Content) will be returned.
|
|
|
|
* For non-AJAX requests, the fallback will always be performed.
|
|
|
|
|
2010-02-16 12:12:53 +00:00
|
|
|
Here's example HTML template code:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
2015-01-12 15:48:49 +00:00
|
|
|
{% load i18n %}
|
2015-06-22 08:58:38 +00:00
|
|
|
|
|
|
|
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
|
2018-01-21 07:09:10 +00:00
|
|
|
<input name="next" type="hidden" value="{{ redirect_to }}">
|
2015-06-22 08:58:38 +00:00
|
|
|
<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 %}
|
2016-09-21 22:12:13 +00:00
|
|
|
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
|
2015-06-22 08:58:38 +00:00
|
|
|
{{ language.name_local }} ({{ language.code }})
|
|
|
|
</option>
|
|
|
|
{% endfor %}
|
|
|
|
</select>
|
2018-01-21 07:09:10 +00:00
|
|
|
<input type="submit" value="Go">
|
2010-02-16 12:12:53 +00:00
|
|
|
</form>
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2012-02-19 09:19:38 +00:00
|
|
|
In this example, Django looks up the URL of the page to which the user will be
|
|
|
|
redirected in the ``redirect_to`` context variable.
|
|
|
|
|
2016-09-12 20:39:34 +00:00
|
|
|
.. _explicitly-setting-the-active-language:
|
|
|
|
|
2014-02-22 13:27:57 +00:00
|
|
|
Explicitly setting the active language
|
|
|
|
--------------------------------------
|
|
|
|
|
|
|
|
.. highlightlang:: python
|
|
|
|
|
|
|
|
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 :func:`django.utils.translation.activate()`. That
|
|
|
|
applies to the current thread only. To persist the language for the entire
|
2016-08-14 20:42:49 +00:00
|
|
|
session in a cookie, set the :setting:`LANGUAGE_COOKIE_NAME` cookie on the
|
|
|
|
response::
|
2014-02-22 13:27:57 +00:00
|
|
|
|
2016-08-14 20:42:49 +00:00
|
|
|
from django.conf import settings
|
|
|
|
from django.http import HttpResponse
|
2014-02-22 13:27:57 +00:00
|
|
|
from django.utils import translation
|
|
|
|
user_language = 'fr'
|
|
|
|
translation.activate(user_language)
|
2016-08-14 20:42:49 +00:00
|
|
|
response = HttpResponse(...)
|
|
|
|
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
|
2014-02-22 13:27:57 +00:00
|
|
|
|
|
|
|
You would typically want to use both: :func:`django.utils.translation.activate()`
|
2016-08-14 20:42:49 +00:00
|
|
|
changes the language for this thread, and setting the cookie makes this
|
2014-02-22 13:27:57 +00:00
|
|
|
preference persist in future requests.
|
|
|
|
|
2016-08-14 20:42:49 +00:00
|
|
|
.. versionchanged:: 3.0
|
2014-02-22 13:27:57 +00:00
|
|
|
|
2016-08-14 20:42:49 +00:00
|
|
|
In older versions, you could set the language in the current session.
|
2014-02-22 13:27:57 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
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
|
2015-04-29 17:43:54 +00:00
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
def welcome_translated(language):
|
|
|
|
cur_language = translation.get_language()
|
|
|
|
try:
|
|
|
|
translation.activate(language)
|
2017-01-26 19:58:33 +00:00
|
|
|
text = translation.gettext('welcome')
|
2011-10-22 17:17:57 +00:00
|
|
|
finally:
|
|
|
|
translation.activate(cur_language)
|
|
|
|
return text
|
|
|
|
|
2018-07-31 15:32:38 +00:00
|
|
|
Calling this function with the value ``'de'`` will give you ``"Willkommen"``,
|
2011-10-22 17:17:57 +00:00
|
|
|
regardless of :setting:`LANGUAGE_CODE` and language set by middleware.
|
|
|
|
|
2015-10-07 08:46:08 +00:00
|
|
|
Functions of particular interest are
|
|
|
|
:func:`django.utils.translation.get_language()` which returns the language used
|
|
|
|
in the current thread, :func:`django.utils.translation.activate()` which
|
|
|
|
activates a translation catalog for the current thread, and
|
|
|
|
:func:`django.utils.translation.check_for_language()`
|
2011-10-22 17:17:57 +00:00
|
|
|
which checks if the given language is supported by Django.
|
|
|
|
|
2015-04-29 17:43:54 +00:00
|
|
|
To help write more concise code, there is also a context manager
|
2015-10-07 08:46:08 +00:00
|
|
|
:func:`django.utils.translation.override()` that stores the current language on
|
2015-04-29 17:43:54 +00:00
|
|
|
enter and restores it on exit. With it, the above example becomes::
|
|
|
|
|
2015-05-02 12:12:20 +00:00
|
|
|
from django.utils import translation
|
2015-04-29 17:43:54 +00:00
|
|
|
|
|
|
|
def welcome_translated(language):
|
|
|
|
with translation.override(language):
|
2017-01-26 19:58:33 +00:00
|
|
|
return translation.gettext('welcome')
|
2015-04-29 17:43:54 +00:00
|
|
|
|
2013-05-19 10:20:34 +00:00
|
|
|
Language cookie
|
|
|
|
---------------
|
|
|
|
|
|
|
|
A number of settings can be used to adjust language cookie options:
|
|
|
|
|
|
|
|
* :setting:`LANGUAGE_COOKIE_NAME`
|
|
|
|
* :setting:`LANGUAGE_COOKIE_AGE`
|
|
|
|
* :setting:`LANGUAGE_COOKIE_DOMAIN`
|
|
|
|
* :setting:`LANGUAGE_COOKIE_PATH`
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
Implementation notes
|
|
|
|
====================
|
|
|
|
|
|
|
|
.. _specialties-of-django-i18n:
|
|
|
|
|
|
|
|
Specialties of Django translation
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
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
|
2015-06-05 12:24:53 +00:00
|
|
|
``django`` domain is used for Python and template translation strings
|
2011-10-22 17:17:57 +00:00
|
|
|
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.
|
|
|
|
|
|
|
|
.. _how-django-discovers-language-preference:
|
|
|
|
|
|
|
|
How Django discovers language preference
|
|
|
|
----------------------------------------
|
|
|
|
|
|
|
|
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 :setting:`LANGUAGE_CODE`.
|
|
|
|
Django uses this language as the default translation -- the final attempt if no
|
2013-08-22 15:14:56 +00:00
|
|
|
better matching translation is found through one of the methods employed by the
|
2013-08-22 11:25:21 +00:00
|
|
|
locale middleware (see below).
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2013-08-22 15:14:56 +00:00
|
|
|
If all you want is to run Django with your native language all you need to do
|
2013-08-22 11:25:21 +00:00
|
|
|
is set :setting:`LANGUAGE_CODE` and make sure the corresponding :term:`message
|
|
|
|
files <message file>` and their compiled versions (``.mo``) exist.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2013-11-30 13:37:15 +00:00
|
|
|
If you want to let each individual user specify which language they
|
2014-04-18 13:05:18 +00:00
|
|
|
prefer, then you also need to use the ``LocaleMiddleware``.
|
2013-08-22 11:25:21 +00:00
|
|
|
``LocaleMiddleware`` enables language selection based on data from the request.
|
|
|
|
It customizes content for each user.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2013-07-19 00:15:30 +00:00
|
|
|
To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
|
2015-11-07 15:12:37 +00:00
|
|
|
to your :setting:`MIDDLEWARE` setting. Because middleware order matters, follow
|
|
|
|
these guidelines:
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2017-08-30 10:25:51 +00:00
|
|
|
* Make sure it's one of the first middleware installed.
|
2011-10-22 17:17:57 +00:00
|
|
|
* 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.
|
|
|
|
|
2015-11-07 15:12:37 +00:00
|
|
|
For example, your :setting:`MIDDLEWARE` might look like this::
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2015-11-07 15:12:37 +00:00
|
|
|
MIDDLEWARE = [
|
2011-10-22 17:17:57 +00:00
|
|
|
'django.contrib.sessions.middleware.SessionMiddleware',
|
|
|
|
'django.middleware.locale.LocaleMiddleware',
|
|
|
|
'django.middleware.common.CommonMiddleware',
|
2015-01-21 16:55:57 +00:00
|
|
|
]
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
(For more on middleware, see the :doc:`middleware documentation
|
|
|
|
</topics/http/middleware>`.)
|
|
|
|
|
|
|
|
``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 :ref:`url-internationalization` for more information
|
|
|
|
about the language prefix and how to internationalize URL patterns.
|
|
|
|
|
|
|
|
* Failing that, it looks for a cookie.
|
|
|
|
|
|
|
|
The name of the cookie used is set by the :setting:`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 :setting:`LANGUAGE_CODE` setting.
|
|
|
|
|
|
|
|
.. _locale-middleware-notes:
|
|
|
|
|
|
|
|
Notes:
|
|
|
|
|
|
|
|
* In each of these places, the language preference is expected to be in the
|
|
|
|
standard :term:`language format<language code>`, 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 :setting:`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 :setting:`LANGUAGES` to a list of languages. For example::
|
|
|
|
|
2015-01-21 16:55:57 +00:00
|
|
|
LANGUAGES = [
|
2011-10-22 17:17:57 +00:00
|
|
|
('de', _('German')),
|
|
|
|
('en', _('English')),
|
2015-01-21 16:55:57 +00:00
|
|
|
]
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
This example restricts languages that are available for automatic
|
2018-07-31 15:32:38 +00:00
|
|
|
selection to German and English (and any sublanguage, like ``de-ch`` or
|
|
|
|
``en-us``).
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
* If you define a custom :setting:`LANGUAGES` setting, as explained in the
|
2013-11-09 10:32:19 +00:00
|
|
|
previous bullet, you can mark the language names as translation strings
|
2017-01-26 19:58:33 +00:00
|
|
|
-- but use :func:`~django.utils.translation.gettext_lazy` instead of
|
|
|
|
:func:`~django.utils.translation.gettext` to avoid a circular import.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2013-11-09 10:32:19 +00:00
|
|
|
Here's a sample settings file::
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2017-01-26 19:58:33 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2015-01-21 16:55:57 +00:00
|
|
|
LANGUAGES = [
|
2013-11-09 10:32:19 +00:00
|
|
|
('de', _('German')),
|
|
|
|
('en', _('English')),
|
2015-01-21 16:55:57 +00:00
|
|
|
]
|
2011-10-22 17:17:57 +00:00
|
|
|
|
|
|
|
Once ``LocaleMiddleware`` determines the user's preference, it makes this
|
|
|
|
preference available as ``request.LANGUAGE_CODE`` for each
|
|
|
|
:class:`~django.http.HttpRequest`. Feel free to read this value in your view
|
|
|
|
code. Here's a simple example::
|
|
|
|
|
2013-05-19 10:42:44 +00:00
|
|
|
from django.http import HttpResponse
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
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``.
|
|
|
|
|
|
|
|
.. _settings file: ../settings/
|
|
|
|
.. _middleware documentation: ../middleware/
|
|
|
|
.. _session: ../sessions/
|
|
|
|
.. _request object: ../request_response/#httprequest-objects
|
|
|
|
|
|
|
|
.. _how-django-discovers-translations:
|
|
|
|
|
|
|
|
How Django discovers translations
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
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
|
|
|
|
:term:`message files <message file>` (``.mo``) and the precedence of multiple
|
|
|
|
translations for the same literal:
|
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. The directories listed in :setting:`LOCALE_PATHS` have the highest
|
2011-10-22 17:17:57 +00:00
|
|
|
precedence, with the ones appearing first having higher precedence than
|
|
|
|
the ones appearing later.
|
2018-11-15 18:54:28 +00:00
|
|
|
#. Then, it looks for and uses if it exists a ``locale`` directory in each
|
2011-10-22 17:17:57 +00:00
|
|
|
of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
|
|
|
|
appearing first have higher precedence than the ones appearing later.
|
2018-11-15 18:54:28 +00:00
|
|
|
#. Finally, the Django-provided base translation in ``django/conf/locale``
|
2011-10-22 17:17:57 +00:00
|
|
|
is used as a fallback.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The translations for literals included in JavaScript assets are looked up
|
2017-09-08 04:19:48 +00:00
|
|
|
following a similar but not identical algorithm. See
|
|
|
|
:class:`.JavaScriptCatalog` for more details.
|
2011-10-22 17:17:57 +00:00
|
|
|
|
2017-11-30 08:12:20 +00:00
|
|
|
You can also put :ref:`custom format files <custom-format-files>` in the
|
|
|
|
:setting:`LOCALE_PATHS` directories if you also set
|
|
|
|
:setting:`FORMAT_MODULE_PATH`.
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
In all cases the name of the directory containing the translation is expected to
|
|
|
|
be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, ``es_AR``,
|
2018-02-19 18:09:33 +00:00
|
|
|
etc. Untranslated strings for territorial language variants use the translations
|
|
|
|
of the generic language. For example, untranslated ``pt_BR`` strings use ``pt``
|
|
|
|
translations.
|
|
|
|
|
2011-10-22 17:17:57 +00:00
|
|
|
This way, you can write applications that include their own translations, and
|
2012-03-31 22:24:24 +00:00
|
|
|
you can override base translations in your project. Or, you can just build
|
2011-10-22 17:17:57 +00:00
|
|
|
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 :setting:`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)``
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
To create message files, you use the :djadmin:`django-admin makemessages <makemessages>`
|
|
|
|
tool. And you use :djadmin:`django-admin compilemessages <compilemessages>`
|
2011-10-22 17:17:57 +00:00
|
|
|
to produce the binary ``.mo`` files that are used by ``gettext``.
|
|
|
|
|
2014-07-26 11:21:52 +00:00
|
|
|
You can also run :djadmin:`django-admin compilemessages
|
2011-10-22 17:17:57 +00:00
|
|
|
--settings=path.to.settings <compilemessages>` to make the compiler process all
|
|
|
|
the directories in your :setting:`LOCALE_PATHS` setting.
|
2016-06-02 16:51:09 +00:00
|
|
|
|
|
|
|
Using a non-English base language
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
Django makes the general assumption that the original strings in a translatable
|
|
|
|
project are written in English. You can choose another language, but you must be
|
|
|
|
aware of certain limitations:
|
|
|
|
|
|
|
|
* ``gettext`` only provides two plural forms for the original messages, so you
|
|
|
|
will also need to provide a translation for the base language to include all
|
|
|
|
plural forms if the plural rules for the base language are different from
|
|
|
|
English.
|
|
|
|
|
|
|
|
* When an English variant is activated and English strings are missing, the
|
|
|
|
fallback language will not be the :setting:`LANGUAGE_CODE` of the project,
|
|
|
|
but the original strings. For example, an English user visiting a site with
|
2018-03-31 23:33:48 +00:00
|
|
|
:setting:`LANGUAGE_CODE` set to Spanish and original strings written in
|
|
|
|
Russian will see Russian text rather than Spanish.
|