1. ===========
    
  2. Translation
    
  3. ===========
    
  4. 
    
  5. .. currentmodule:: django.utils.translation
    
  6. 
    
  7. Overview
    
  8. ========
    
  9. 
    
  10. In order to make a Django project translatable, you have to add a minimal
    
  11. number of hooks to your Python code and templates. These hooks are called
    
  12. :term:`translation strings <translation string>`. They tell Django: "This text
    
  13. should be translated into the end user's language, if a translation for this
    
  14. text is available in that language." It's your responsibility to mark
    
  15. translatable strings; the system can only translate strings it knows about.
    
  16. 
    
  17. Django then provides utilities to extract the translation strings into a
    
  18. :term:`message file`. This file is a convenient way for translators to provide
    
  19. the equivalent of the translation strings in the target language. Once the
    
  20. translators have filled in the message file, it must be compiled. This process
    
  21. relies on the GNU gettext toolset.
    
  22. 
    
  23. Once this is done, Django takes care of translating web apps on the fly in each
    
  24. available language, according to users' language preferences.
    
  25. 
    
  26. Django's internationalization hooks are on by default, and that means there's a
    
  27. bit of i18n-related overhead in certain places of the framework. If you don't
    
  28. use internationalization, you should take the two seconds to set
    
  29. :setting:`USE_I18N = False <USE_I18N>` in your settings file. Then Django will
    
  30. make some optimizations so as not to load the internationalization machinery.
    
  31. 
    
  32. .. note::
    
  33. 
    
  34.     Make sure you've activated translation for your project (the fastest way is
    
  35.     to check if :setting:`MIDDLEWARE` includes
    
  36.     :mod:`django.middleware.locale.LocaleMiddleware`). If you haven't yet,
    
  37.     see :ref:`how-django-discovers-language-preference`.
    
  38. 
    
  39. Internationalization: in Python code
    
  40. ====================================
    
  41. 
    
  42. Standard translation
    
  43. --------------------
    
  44. 
    
  45. Specify a translation string by using the function
    
  46. :func:`~django.utils.translation.gettext`. It's convention to import this
    
  47. as a shorter alias, ``_``, to save typing.
    
  48. 
    
  49. .. note::
    
  50.     Python's standard library ``gettext`` module installs ``_()`` into the
    
  51.     global namespace, as an alias for ``gettext()``. In Django, we have chosen
    
  52.     not to follow this practice, for a couple of reasons:
    
  53. 
    
  54.     #. Sometimes, you should use :func:`~django.utils.translation.gettext_lazy`
    
  55.        as the default translation method for a particular file. Without ``_()``
    
  56.        in the global namespace, the developer has to think about which is the
    
  57.        most appropriate translation function.
    
  58. 
    
  59.     #. The underscore character (``_``) is used to represent "the previous
    
  60.        result" in Python's interactive shell and doctest tests. Installing a
    
  61.        global ``_()`` function causes interference. Explicitly importing
    
  62.        ``gettext()`` as ``_()`` avoids this problem.
    
  63. 
    
  64. .. admonition:: What functions may be aliased as ``_``?
    
  65. 
    
  66.     Because of how ``xgettext`` (used by :djadmin:`makemessages`) works, only
    
  67.     functions that take a single string argument can be imported as ``_``:
    
  68. 
    
  69.     * :func:`~django.utils.translation.gettext`
    
  70.     * :func:`~django.utils.translation.gettext_lazy`
    
  71. 
    
  72. In this example, the text ``"Welcome to my site."`` is marked as a translation
    
  73. string::
    
  74. 
    
  75.     from django.http import HttpResponse
    
  76.     from django.utils.translation import gettext as _
    
  77. 
    
  78.     def my_view(request):
    
  79.         output = _("Welcome to my site.")
    
  80.         return HttpResponse(output)
    
  81. 
    
  82. You could code this without using the alias. This example is identical to the
    
  83. previous one::
    
  84. 
    
  85.     from django.http import HttpResponse
    
  86.     from django.utils.translation import gettext
    
  87. 
    
  88.     def my_view(request):
    
  89.         output = gettext("Welcome to my site.")
    
  90.         return HttpResponse(output)
    
  91. 
    
  92. Translation works on computed values. This example is identical to the previous
    
  93. two::
    
  94. 
    
  95.     def my_view(request):
    
  96.         words = ['Welcome', 'to', 'my', 'site.']
    
  97.         output = _(' '.join(words))
    
  98.         return HttpResponse(output)
    
  99. 
    
  100. Translation works on variables. Again, here's an identical example::
    
  101. 
    
  102.     def my_view(request):
    
  103.         sentence = 'Welcome to my site.'
    
  104.         output = _(sentence)
    
  105.         return HttpResponse(output)
    
  106. 
    
  107. (The caveat with using variables or computed values, as in the previous two
    
  108. examples, is that Django's translation-string-detecting utility,
    
  109. :djadmin:`django-admin makemessages <makemessages>`, won't be able to find
    
  110. these strings. More on :djadmin:`makemessages` later.)
    
  111. 
    
  112. The strings you pass to ``_()`` or ``gettext()`` can take placeholders,
    
  113. specified with Python's standard named-string interpolation syntax. Example::
    
  114. 
    
  115.     def my_view(request, m, d):
    
  116.         output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
    
  117.         return HttpResponse(output)
    
  118. 
    
  119. This technique lets language-specific translations reorder the placeholder
    
  120. text. For example, an English translation may be ``"Today is November 26."``,
    
  121. while a Spanish translation may be ``"Hoy es 26 de noviembre."`` -- with the
    
  122. month and the day placeholders swapped.
    
  123. 
    
  124. For this reason, you should use named-string interpolation (e.g., ``%(day)s``)
    
  125. instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
    
  126. have more than a single parameter. If you used positional interpolation,
    
  127. translations wouldn't be able to reorder placeholder text.
    
  128. 
    
  129. Since string extraction is done by the ``xgettext`` command, only syntaxes
    
  130. supported by ``gettext`` are supported by Django. In particular, Python
    
  131. :py:ref:`f-strings <f-strings>` are not yet supported by ``xgettext``, and
    
  132. JavaScript template strings need ``gettext`` 0.21+.
    
  133. 
    
  134. .. _translator-comments:
    
  135. 
    
  136. Comments for translators
    
  137. ------------------------
    
  138. 
    
  139. If you would like to give translators hints about a translatable string, you
    
  140. can add a comment prefixed with the ``Translators`` keyword on the line
    
  141. preceding the string, e.g.::
    
  142. 
    
  143.     def my_view(request):
    
  144.         # Translators: This message appears on the home page only
    
  145.         output = gettext("Welcome to my site.")
    
  146. 
    
  147. The comment will then appear in the resulting ``.po`` file associated with the
    
  148. translatable construct located below it and should also be displayed by most
    
  149. translation tools.
    
  150. 
    
  151. .. note:: Just for completeness, this is the corresponding fragment of the
    
  152.     resulting ``.po`` file:
    
  153. 
    
  154.     .. code-block:: po
    
  155. 
    
  156.         #. Translators: This message appears on the home page only
    
  157.         # path/to/python/file.py:123
    
  158.         msgid "Welcome to my site."
    
  159.         msgstr ""
    
  160. 
    
  161. This also works in templates. See :ref:`translator-comments-in-templates` for
    
  162. more details.
    
  163. 
    
  164. Marking strings as no-op
    
  165. ------------------------
    
  166. 
    
  167. Use the function :func:`django.utils.translation.gettext_noop()` to mark a
    
  168. string as a translation string without translating it. The string is later
    
  169. translated from a variable.
    
  170. 
    
  171. Use this if you have constant strings that should be stored in the source
    
  172. language because they are exchanged over systems or users -- such as strings
    
  173. in a database -- but should be translated at the last possible point in time,
    
  174. such as when the string is presented to the user.
    
  175. 
    
  176. Pluralization
    
  177. -------------
    
  178. 
    
  179. Use the function :func:`django.utils.translation.ngettext()` to specify
    
  180. pluralized messages.
    
  181. 
    
  182. ``ngettext()`` takes three arguments: the singular translation string, the
    
  183. plural translation string and the number of objects.
    
  184. 
    
  185. This function is useful when you need your Django application to be localizable
    
  186. to languages where the number and complexity of `plural forms
    
  187. <https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
    
  188. greater than the two forms used in English ('object' for the singular and
    
  189. 'objects' for all the cases where ``count`` is different from one, irrespective
    
  190. of its value.)
    
  191. 
    
  192. For example::
    
  193. 
    
  194.     from django.http import HttpResponse
    
  195.     from django.utils.translation import ngettext
    
  196. 
    
  197.     def hello_world(request, count):
    
  198.         page = ngettext(
    
  199.             'there is %(count)d object',
    
  200.             'there are %(count)d objects',
    
  201.             count,
    
  202.         ) % {
    
  203.             'count': count,
    
  204.         }
    
  205.         return HttpResponse(page)
    
  206. 
    
  207. In this example the number of objects is passed to the translation
    
  208. languages as the ``count`` variable.
    
  209. 
    
  210. Note that pluralization is complicated and works differently in each language.
    
  211. Comparing ``count`` to 1 isn't always the correct rule. This code looks
    
  212. sophisticated, but will produce incorrect results for some languages::
    
  213. 
    
  214.     from django.utils.translation import ngettext
    
  215.     from myapp.models import Report
    
  216. 
    
  217.     count = Report.objects.count()
    
  218.     if count == 1:
    
  219.         name = Report._meta.verbose_name
    
  220.     else:
    
  221.         name = Report._meta.verbose_name_plural
    
  222. 
    
  223.     text = ngettext(
    
  224.         'There is %(count)d %(name)s available.',
    
  225.         'There are %(count)d %(name)s available.',
    
  226.         count,
    
  227.     ) % {
    
  228.         'count': count,
    
  229.         'name': name
    
  230.     }
    
  231. 
    
  232. Don't try to implement your own singular-or-plural logic; it won't be correct.
    
  233. In a case like this, consider something like the following::
    
  234. 
    
  235.     text = ngettext(
    
  236.         'There is %(count)d %(name)s object available.',
    
  237.         'There are %(count)d %(name)s objects available.',
    
  238.         count,
    
  239.     ) % {
    
  240.         'count': count,
    
  241.         'name': Report._meta.verbose_name,
    
  242.     }
    
  243. 
    
  244. .. _pluralization-var-notes:
    
  245. 
    
  246. .. note::
    
  247. 
    
  248.     When using ``ngettext()``, make sure you use a single name for every
    
  249.     extrapolated variable included in the literal. In the examples above, note
    
  250.     how we used the ``name`` Python variable in both translation strings. This
    
  251.     example, besides being incorrect in some languages as noted above, would
    
  252.     fail::
    
  253. 
    
  254.         text = ngettext(
    
  255.             'There is %(count)d %(name)s available.',
    
  256.             'There are %(count)d %(plural_name)s available.',
    
  257.             count,
    
  258.         ) % {
    
  259.             'count': Report.objects.count(),
    
  260.             'name': Report._meta.verbose_name,
    
  261.             'plural_name': Report._meta.verbose_name_plural,
    
  262.         }
    
  263. 
    
  264.     You would get an error when running :djadmin:`django-admin
    
  265.     compilemessages <compilemessages>`::
    
  266. 
    
  267.         a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'
    
  268. 
    
  269. .. _contextual-markers:
    
  270. 
    
  271. Contextual markers
    
  272. ------------------
    
  273. 
    
  274. Sometimes words have several meanings, such as ``"May"`` in English, which
    
  275. refers to a month name and to a verb. To enable translators to translate
    
  276. these words correctly in different contexts, you can use the
    
  277. :func:`django.utils.translation.pgettext()` function, or the
    
  278. :func:`django.utils.translation.npgettext()` function if the string needs
    
  279. pluralization. Both take a context string as the first variable.
    
  280. 
    
  281. In the resulting ``.po`` file, the string will then appear as often as there are
    
  282. different contextual markers for the same string (the context will appear on the
    
  283. ``msgctxt`` line), allowing the translator to give a different translation for
    
  284. each of them.
    
  285. 
    
  286. For example::
    
  287. 
    
  288.     from django.utils.translation import pgettext
    
  289. 
    
  290.     month = pgettext("month name", "May")
    
  291. 
    
  292. or::
    
  293. 
    
  294.     from django.db import models
    
  295.     from django.utils.translation import pgettext_lazy
    
  296. 
    
  297.     class MyThing(models.Model):
    
  298.         name = models.CharField(help_text=pgettext_lazy(
    
  299.             'help text for MyThing model', 'This is the help text'))
    
  300. 
    
  301. will appear in the ``.po`` file as:
    
  302. 
    
  303. .. code-block:: po
    
  304. 
    
  305.     msgctxt "month name"
    
  306.     msgid "May"
    
  307.     msgstr ""
    
  308. 
    
  309. Contextual markers are also supported by the :ttag:`translate` and
    
  310. :ttag:`blocktranslate` template tags.
    
  311. 
    
  312. .. _lazy-translations:
    
  313. 
    
  314. Lazy translation
    
  315. ----------------
    
  316. 
    
  317. Use the lazy versions of translation functions in
    
  318. :mod:`django.utils.translation` (easily recognizable by the ``lazy`` suffix in
    
  319. their names) to translate strings lazily -- when the value is accessed rather
    
  320. than when they're called.
    
  321. 
    
  322. These functions store a lazy reference to the string -- not the actual
    
  323. translation. The translation itself will be done when the string is used in a
    
  324. string context, such as in template rendering.
    
  325. 
    
  326. This is essential when calls to these functions are located in code paths that
    
  327. are executed at module load time.
    
  328. 
    
  329. This is something that can easily happen when defining models, forms and
    
  330. model forms, because Django implements these such that their fields are
    
  331. actually class-level attributes. For that reason, make sure to use lazy
    
  332. translations in the following cases:
    
  333. 
    
  334. Model fields and relationships ``verbose_name`` and ``help_text`` option values
    
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  336. 
    
  337. For example, to translate the help text of the *name* field in the following
    
  338. model, do the following::
    
  339. 
    
  340.     from django.db import models
    
  341.     from django.utils.translation import gettext_lazy as _
    
  342. 
    
  343.     class MyThing(models.Model):
    
  344.         name = models.CharField(help_text=_('This is the help text'))
    
  345. 
    
  346. You can mark names of :class:`~django.db.models.ForeignKey`,
    
  347. :class:`~django.db.models.ManyToManyField` or
    
  348. :class:`~django.db.models.OneToOneField` relationship as translatable by using
    
  349. their :attr:`~django.db.models.Options.verbose_name` options::
    
  350. 
    
  351.     class MyThing(models.Model):
    
  352.         kind = models.ForeignKey(
    
  353.             ThingKind,
    
  354.             on_delete=models.CASCADE,
    
  355.             related_name='kinds',
    
  356.             verbose_name=_('kind'),
    
  357.         )
    
  358. 
    
  359. Just like you would do in :attr:`~django.db.models.Options.verbose_name` you
    
  360. should provide a lowercase verbose name text for the relation as Django will
    
  361. automatically titlecase it when required.
    
  362. 
    
  363. Model verbose names values
    
  364. ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  365. 
    
  366. It is recommended to always provide explicit
    
  367. :attr:`~django.db.models.Options.verbose_name` and
    
  368. :attr:`~django.db.models.Options.verbose_name_plural` options rather than
    
  369. relying on the fallback English-centric and somewhat naïve determination of
    
  370. verbose names Django performs by looking at the model's class name::
    
  371. 
    
  372.     from django.db import models
    
  373.     from django.utils.translation import gettext_lazy as _
    
  374. 
    
  375.     class MyThing(models.Model):
    
  376.         name = models.CharField(_('name'), help_text=_('This is the help text'))
    
  377. 
    
  378.         class Meta:
    
  379.             verbose_name = _('my thing')
    
  380.             verbose_name_plural = _('my things')
    
  381. 
    
  382. Model methods ``description`` argument to the ``@display`` decorator
    
  383. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  384. 
    
  385. For model methods, you can provide translations to Django and the admin site
    
  386. with the ``description`` argument to the :func:`~django.contrib.admin.display`
    
  387. decorator::
    
  388. 
    
  389.     from django.contrib import admin
    
  390.     from django.db import models
    
  391.     from django.utils.translation import gettext_lazy as _
    
  392. 
    
  393.     class MyThing(models.Model):
    
  394.         kind = models.ForeignKey(
    
  395.             ThingKind,
    
  396.             on_delete=models.CASCADE,
    
  397.             related_name='kinds',
    
  398.             verbose_name=_('kind'),
    
  399.         )
    
  400. 
    
  401.         @admin.display(description=_('Is it a mouse?'))
    
  402.         def is_mouse(self):
    
  403.             return self.kind.type == MOUSE_TYPE
    
  404. 
    
  405. Working with lazy translation objects
    
  406. -------------------------------------
    
  407. 
    
  408. The result of a ``gettext_lazy()`` call can be used wherever you would use a
    
  409. string (a :class:`str` object) in other Django code, but it may not work with
    
  410. arbitrary Python code. For example, the following won't work because the
    
  411. `requests <https://pypi.org/project/requests/>`_ library doesn't handle
    
  412. ``gettext_lazy`` objects::
    
  413. 
    
  414.     body = gettext_lazy("I \u2764 Django")  # (Unicode :heart:)
    
  415.     requests.post('https://example.com/send', data={'body': body})
    
  416. 
    
  417. You can avoid such problems by casting ``gettext_lazy()`` objects to text
    
  418. strings before passing them to non-Django code::
    
  419. 
    
  420.     requests.post('https://example.com/send', data={'body': str(body)})
    
  421. 
    
  422. If you don't like the long ``gettext_lazy`` name, you can alias it as ``_``
    
  423. (underscore), like so::
    
  424. 
    
  425.     from django.db import models
    
  426.     from django.utils.translation import gettext_lazy as _
    
  427. 
    
  428.     class MyThing(models.Model):
    
  429.         name = models.CharField(help_text=_('This is the help text'))
    
  430. 
    
  431. Using ``gettext_lazy()`` and ``ngettext_lazy()`` to mark strings in models
    
  432. and utility functions is a common operation. When you're working with these
    
  433. objects elsewhere in your code, you should ensure that you don't accidentally
    
  434. convert them to strings, because they should be converted as late as possible
    
  435. (so that the correct locale is in effect). This necessitates the use of the
    
  436. helper function described next.
    
  437. 
    
  438. .. _lazy-plural-translations:
    
  439. 
    
  440. Lazy translations and plural
    
  441. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  442. 
    
  443. When using lazy translation for a plural string (``n[p]gettext_lazy``), you
    
  444. generally don't know the ``number`` argument at the time of the string
    
  445. definition. Therefore, you are authorized to pass a key name instead of an
    
  446. integer as the ``number`` argument. Then ``number`` will be looked up in the
    
  447. dictionary under that key during string interpolation. Here's example::
    
  448. 
    
  449.     from django import forms
    
  450.     from django.core.exceptions import ValidationError
    
  451.     from django.utils.translation import ngettext_lazy
    
  452. 
    
  453.     class MyForm(forms.Form):
    
  454.         error_message = ngettext_lazy("You only provided %(num)d argument",
    
  455.             "You only provided %(num)d arguments", 'num')
    
  456. 
    
  457.         def clean(self):
    
  458.             # ...
    
  459.             if error:
    
  460.                 raise ValidationError(self.error_message % {'num': number})
    
  461. 
    
  462. If the string contains exactly one unnamed placeholder, you can interpolate
    
  463. directly with the ``number`` argument::
    
  464. 
    
  465.     class MyForm(forms.Form):
    
  466.         error_message = ngettext_lazy(
    
  467.             "You provided %d argument",
    
  468.             "You provided %d arguments",
    
  469.         )
    
  470. 
    
  471.         def clean(self):
    
  472.             # ...
    
  473.             if error:
    
  474.                 raise ValidationError(self.error_message % number)
    
  475. 
    
  476. 
    
  477. Formatting strings: ``format_lazy()``
    
  478. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  479. 
    
  480. Python's :meth:`str.format()` method will not work when either the
    
  481. ``format_string`` or any of the arguments to :meth:`str.format()`
    
  482. contains lazy translation objects. Instead, you can use
    
  483. :func:`django.utils.text.format_lazy()`, which creates a lazy object
    
  484. that runs the ``str.format()`` method only when the result is included
    
  485. in a string. For example::
    
  486. 
    
  487.     from django.utils.text import format_lazy
    
  488.     from django.utils.translation import gettext_lazy
    
  489.     ...
    
  490.     name = gettext_lazy('John Lennon')
    
  491.     instrument = gettext_lazy('guitar')
    
  492.     result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)
    
  493. 
    
  494. In this case, the lazy translations in ``result`` will only be converted to
    
  495. strings when ``result`` itself is used in a string (usually at template
    
  496. rendering time).
    
  497. 
    
  498. Other uses of lazy in delayed translations
    
  499. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  500. 
    
  501. For any other case where you would like to delay the translation, but have to
    
  502. pass the translatable string as argument to another function, you can wrap
    
  503. this function inside a lazy call yourself. For example::
    
  504. 
    
  505.     from django.utils.functional import lazy
    
  506.     from django.utils.safestring import mark_safe
    
  507.     from django.utils.translation import gettext_lazy as _
    
  508. 
    
  509.     mark_safe_lazy = lazy(mark_safe, str)
    
  510. 
    
  511. And then later::
    
  512. 
    
  513.     lazy_string = mark_safe_lazy(_("<p>My <strong>string!</strong></p>"))
    
  514. 
    
  515. Localized names of languages
    
  516. ----------------------------
    
  517. 
    
  518. .. function:: get_language_info(lang_code)
    
  519. 
    
  520. The ``get_language_info()`` function provides detailed information about
    
  521. languages::
    
  522. 
    
  523.     >>> from django.utils.translation import activate, get_language_info
    
  524.     >>> activate('fr')
    
  525.     >>> li = get_language_info('de')
    
  526.     >>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])
    
  527.     German Deutsch Allemand False
    
  528. 
    
  529. The ``name``, ``name_local``, and ``name_translated`` attributes of the
    
  530. dictionary contain the name of the language in English, in the language
    
  531. itself, and in your current active language respectively.  The ``bidi``
    
  532. attribute is True only for bi-directional languages.
    
  533. 
    
  534. The source of the language information is the ``django.conf.locale`` module.
    
  535. Similar access to this information is available for template code. See below.
    
  536. 
    
  537. .. _specifying-translation-strings-in-template-code:
    
  538. 
    
  539. Internationalization: in template code
    
  540. ======================================
    
  541. 
    
  542. .. highlight:: html+django
    
  543. 
    
  544. Translations in :doc:`Django templates </ref/templates/language>` uses two template
    
  545. tags and a slightly different syntax than in Python code. To give your template
    
  546. access to these tags, put ``{% load i18n %}`` toward the top of your template.
    
  547. As with all template tags, this tag needs to be loaded in all templates which
    
  548. use translations, even those templates that extend from other templates which
    
  549. have already loaded the ``i18n`` tag.
    
  550. 
    
  551. .. warning::
    
  552. 
    
  553.     Translated strings will not be escaped when rendered in a template.
    
  554.     This allows you to include HTML in translations, for example for emphasis,
    
  555.     but potentially dangerous characters (e.g. ``"``) will also be rendered
    
  556.     unchanged.
    
  557. 
    
  558. .. templatetag:: trans
    
  559. .. templatetag:: translate
    
  560. 
    
  561. ``translate`` template tag
    
  562. --------------------------
    
  563. 
    
  564. The ``{% translate %}`` template tag translates either a constant string
    
  565. (enclosed in single or double quotes) or variable content::
    
  566. 
    
  567.     <title>{% translate "This is the title." %}</title>
    
  568.     <title>{% translate myvar %}</title>
    
  569. 
    
  570. If the ``noop`` option is present, variable lookup still takes place but the
    
  571. translation is skipped. This is useful when "stubbing out" content that will
    
  572. require translation in the future::
    
  573. 
    
  574.     <title>{% translate "myvar" noop %}</title>
    
  575. 
    
  576. Internally, inline translations use a
    
  577. :func:`~django.utils.translation.gettext` call.
    
  578. 
    
  579. In case a template var (``myvar`` above) is passed to the tag, the tag will
    
  580. first resolve such variable to a string at run-time and then look up that
    
  581. string in the message catalogs.
    
  582. 
    
  583. It's not possible to mix a template variable inside a string within
    
  584. ``{% translate %}``. If your translations require strings with variables
    
  585. (placeholders), use :ttag:`{% blocktranslate %}<blocktranslate>` instead.
    
  586. 
    
  587. If you'd like to retrieve a translated string without displaying it, you can
    
  588. use the following syntax::
    
  589. 
    
  590.     {% translate "This is the title" as the_title %}
    
  591. 
    
  592.     <title>{{ the_title }}</title>
    
  593.     <meta name="description" content="{{ the_title }}">
    
  594. 
    
  595. In practice you'll use this to get a string you can use in multiple places in a
    
  596. template or so you can use the output as an argument for other template tags or
    
  597. filters::
    
  598. 
    
  599.     {% translate "starting point" as start %}
    
  600.     {% translate "end point" as end %}
    
  601.     {% translate "La Grande Boucle" as race %}
    
  602. 
    
  603.     <h1>
    
  604.       <a href="/" title="{% blocktranslate %}Back to '{{ race }}' homepage{% endblocktranslate %}">{{ race }}</a>
    
  605.     </h1>
    
  606.     <p>
    
  607.     {% for stage in tour_stages %}
    
  608.         {% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br>{% else %}, {% endif %}
    
  609.     {% endfor %}
    
  610.     </p>
    
  611. 
    
  612. ``{% translate %}`` also supports :ref:`contextual markers<contextual-markers>`
    
  613. using the ``context`` keyword:
    
  614. 
    
  615. .. code-block:: html+django
    
  616. 
    
  617.     {% translate "May" context "month name" %}
    
  618. 
    
  619. .. templatetag:: blocktrans
    
  620. .. templatetag:: blocktranslate
    
  621. 
    
  622. ``blocktranslate`` template tag
    
  623. -------------------------------
    
  624. 
    
  625. Contrarily to the :ttag:`translate` tag, the ``blocktranslate`` tag allows you
    
  626. to mark complex sentences consisting of literals and variable content for
    
  627. translation by making use of placeholders::
    
  628. 
    
  629.     {% blocktranslate %}This string will have {{ value }} inside.{% endblocktranslate %}
    
  630. 
    
  631. To translate a template expression -- say, accessing object attributes or
    
  632. using template filters -- you need to bind the expression to a local variable
    
  633. for use within the translation block. Examples::
    
  634. 
    
  635.     {% blocktranslate with amount=article.price %}
    
  636.     That will cost $ {{ amount }}.
    
  637.     {% endblocktranslate %}
    
  638. 
    
  639.     {% blocktranslate with myvar=value|filter %}
    
  640.     This will have {{ myvar }} inside.
    
  641.     {% endblocktranslate %}
    
  642. 
    
  643. You can use multiple expressions inside a single ``blocktranslate`` tag::
    
  644. 
    
  645.     {% blocktranslate with book_t=book|title author_t=author|title %}
    
  646.     This is {{ book_t }} by {{ author_t }}
    
  647.     {% endblocktranslate %}
    
  648. 
    
  649. .. note:: The previous more verbose format is still supported:
    
  650.    ``{% blocktranslate with book|title as book_t and author|title as author_t %}``
    
  651. 
    
  652. Other block tags (for example ``{% for %}`` or ``{% if %}``) are not allowed
    
  653. inside a ``blocktranslate`` tag.
    
  654. 
    
  655. If resolving one of the block arguments fails, ``blocktranslate`` will fall
    
  656. back to the default language by deactivating the currently active language
    
  657. temporarily with the :func:`~django.utils.translation.deactivate_all`
    
  658. function.
    
  659. 
    
  660. This tag also provides for pluralization. To use it:
    
  661. 
    
  662. * Designate and bind a counter value with the name ``count``. This value will
    
  663.   be the one used to select the right plural form.
    
  664. 
    
  665. * Specify both the singular and plural forms separating them with the
    
  666.   ``{% plural %}`` tag within the ``{% blocktranslate %}`` and
    
  667.   ``{% endblocktranslate %}`` tags.
    
  668. 
    
  669. An example::
    
  670. 
    
  671.     {% blocktranslate count counter=list|length %}
    
  672.     There is only one {{ name }} object.
    
  673.     {% plural %}
    
  674.     There are {{ counter }} {{ name }} objects.
    
  675.     {% endblocktranslate %}
    
  676. 
    
  677. A more complex example::
    
  678. 
    
  679.     {% blocktranslate with amount=article.price count years=i.length %}
    
  680.     That will cost $ {{ amount }} per year.
    
  681.     {% plural %}
    
  682.     That will cost $ {{ amount }} per {{ years }} years.
    
  683.     {% endblocktranslate %}
    
  684. 
    
  685. When you use both the pluralization feature and bind values to local variables
    
  686. in addition to the counter value, keep in mind that the ``blocktranslate``
    
  687. construct is internally converted to an ``ngettext`` call. This means the
    
  688. same :ref:`notes regarding ngettext variables <pluralization-var-notes>`
    
  689. apply.
    
  690. 
    
  691. Reverse URL lookups cannot be carried out within the ``blocktranslate`` and
    
  692. should be retrieved (and stored) beforehand::
    
  693. 
    
  694.     {% url 'path.to.view' arg arg2 as the_url %}
    
  695.     {% blocktranslate %}
    
  696.     This is a URL: {{ the_url }}
    
  697.     {% endblocktranslate %}
    
  698. 
    
  699. If you'd like to retrieve a translated string without displaying it, you can
    
  700. use the following syntax::
    
  701. 
    
  702.     {% blocktranslate asvar the_title %}The title is {{ title }}.{% endblocktranslate %}
    
  703.     <title>{{ the_title }}</title>
    
  704.     <meta name="description" content="{{ the_title }}">
    
  705. 
    
  706. In practice you'll use this to get a string you can use in multiple places in a
    
  707. template or so you can use the output as an argument for other template tags or
    
  708. filters.
    
  709. 
    
  710. ``{% blocktranslate %}`` also supports :ref:`contextual
    
  711. markers<contextual-markers>` using the ``context`` keyword:
    
  712. 
    
  713. .. code-block:: html+django
    
  714. 
    
  715.     {% blocktranslate with name=user.username context "greeting" %}Hi {{ name }}{% endblocktranslate %}
    
  716. 
    
  717. Another feature ``{% blocktranslate %}`` supports is the ``trimmed`` option.
    
  718. This option will remove newline characters from the beginning and the end of
    
  719. the content of the ``{% blocktranslate %}`` tag, replace any whitespace at the
    
  720. beginning and end of a line and merge all lines into one using a space
    
  721. character to separate them. This is quite useful for indenting the content of a
    
  722. ``{% blocktranslate %}`` tag without having the indentation characters end up
    
  723. in the corresponding entry in the ``.po`` file, which makes the translation
    
  724. process easier.
    
  725. 
    
  726. For instance, the following ``{% blocktranslate %}`` tag::
    
  727. 
    
  728.     {% blocktranslate trimmed %}
    
  729.       First sentence.
    
  730.       Second paragraph.
    
  731.     {% endblocktranslate %}
    
  732. 
    
  733. will result in the entry ``"First sentence. Second paragraph."`` in the ``.po``
    
  734. file, compared to ``"\n  First sentence.\n  Second paragraph.\n"``, if the
    
  735. ``trimmed`` option had not been specified.
    
  736. 
    
  737. String literals passed to tags and filters
    
  738. ------------------------------------------
    
  739. 
    
  740. You can translate string literals passed as arguments to tags and filters
    
  741. by using the familiar ``_()`` syntax::
    
  742. 
    
  743.     {% some_tag _("Page not found") value|yesno:_("yes,no") %}
    
  744. 
    
  745. In this case, both the tag and the filter will see the translated string,
    
  746. so they don't need to be aware of translations.
    
  747. 
    
  748. .. note::
    
  749.     In this example, the translation infrastructure will be passed the string
    
  750.     ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
    
  751.     translated string will need to contain the comma so that the filter
    
  752.     parsing code knows how to split up the arguments. For example, a German
    
  753.     translator might translate the string ``"yes,no"`` as ``"ja,nein"``
    
  754.     (keeping the comma intact).
    
  755. 
    
  756. .. _translator-comments-in-templates:
    
  757. 
    
  758. Comments for translators in templates
    
  759. -------------------------------------
    
  760. 
    
  761. Just like with :ref:`Python code <translator-comments>`, these notes for
    
  762. translators can be specified using comments, either with the :ttag:`comment`
    
  763. tag:
    
  764. 
    
  765. .. code-block:: html+django
    
  766. 
    
  767.     {% comment %}Translators: View verb{% endcomment %}
    
  768.     {% translate "View" %}
    
  769. 
    
  770.     {% comment %}Translators: Short intro blurb{% endcomment %}
    
  771.     <p>{% blocktranslate %}A multiline translatable
    
  772.     literal.{% endblocktranslate %}</p>
    
  773. 
    
  774. or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:
    
  775. 
    
  776. .. code-block:: html+django
    
  777. 
    
  778.     {# Translators: Label of a button that triggers search #}
    
  779.     <button type="submit">{% translate "Go" %}</button>
    
  780. 
    
  781.     {# Translators: This is a text of the base template #}
    
  782.     {% blocktranslate %}Ambiguous translatable block of text{% endblocktranslate %}
    
  783. 
    
  784. .. note:: Just for completeness, these are the corresponding fragments of the
    
  785.     resulting ``.po`` file:
    
  786. 
    
  787.     .. code-block:: po
    
  788. 
    
  789.         #. Translators: View verb
    
  790.         # path/to/template/file.html:10
    
  791.         msgid "View"
    
  792.         msgstr ""
    
  793. 
    
  794.         #. Translators: Short intro blurb
    
  795.         # path/to/template/file.html:13
    
  796.         msgid ""
    
  797.         "A multiline translatable"
    
  798.         "literal."
    
  799.         msgstr ""
    
  800. 
    
  801.         # ...
    
  802. 
    
  803.         #. Translators: Label of a button that triggers search
    
  804.         # path/to/template/file.html:100
    
  805.         msgid "Go"
    
  806.         msgstr ""
    
  807. 
    
  808.         #. Translators: This is a text of the base template
    
  809.         # path/to/template/file.html:103
    
  810.         msgid "Ambiguous translatable block of text"
    
  811.         msgstr ""
    
  812. 
    
  813. .. templatetag:: language
    
  814. 
    
  815. Switching language in templates
    
  816. -------------------------------
    
  817. 
    
  818. If you want to select a language within a template, you can use the
    
  819. ``language`` template tag:
    
  820. 
    
  821. .. code-block:: html+django
    
  822. 
    
  823.     {% load i18n %}
    
  824. 
    
  825.     {% get_current_language as LANGUAGE_CODE %}
    
  826.     <!-- Current language: {{ LANGUAGE_CODE }} -->
    
  827.     <p>{% translate "Welcome to our page" %}</p>
    
  828. 
    
  829.     {% language 'en' %}
    
  830.         {% get_current_language as LANGUAGE_CODE %}
    
  831.         <!-- Current language: {{ LANGUAGE_CODE }} -->
    
  832.         <p>{% translate "Welcome to our page" %}</p>
    
  833.     {% endlanguage %}
    
  834. 
    
  835. While the first occurrence of "Welcome to our page" uses the current language,
    
  836. the second will always be in English.
    
  837. 
    
  838. .. _i18n-template-tags:
    
  839. 
    
  840. Other tags
    
  841. ----------
    
  842. 
    
  843. These tags also require a ``{% load i18n %}``.
    
  844. 
    
  845. .. templatetag:: get_available_languages
    
  846. 
    
  847. ``get_available_languages``
    
  848. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  849. 
    
  850. ``{% get_available_languages as LANGUAGES %}`` returns a list of tuples in
    
  851. which the first element is the :term:`language code` and the second is the
    
  852. language name (translated into the currently active locale).
    
  853. 
    
  854. .. templatetag:: get_current_language
    
  855. 
    
  856. ``get_current_language``
    
  857. ~~~~~~~~~~~~~~~~~~~~~~~~
    
  858. 
    
  859. ``{% get_current_language as LANGUAGE_CODE %}`` returns the current user's
    
  860. preferred language as a string. Example: ``en-us``. See
    
  861. :ref:`how-django-discovers-language-preference`.
    
  862. 
    
  863. .. templatetag:: get_current_language_bidi
    
  864. 
    
  865. ``get_current_language_bidi``
    
  866. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  867. 
    
  868. ``{% get_current_language_bidi as LANGUAGE_BIDI %}`` returns the current
    
  869. locale's direction. If ``True``, it's a right-to-left language, e.g. Hebrew,
    
  870. Arabic. If ``False`` it's a left-to-right language, e.g. English, French,
    
  871. German, etc.
    
  872. 
    
  873. .. _template-translation-vars:
    
  874. 
    
  875. ``i18n`` context processor
    
  876. ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  877. 
    
  878. If you enable the :class:`django.template.context_processors.i18n` context
    
  879. processor, then each ``RequestContext`` will have access to ``LANGUAGES``,
    
  880. ``LANGUAGE_CODE``, and ``LANGUAGE_BIDI`` as defined above.
    
  881. 
    
  882. .. templatetag:: get_language_info
    
  883. 
    
  884. ``get_language_info``
    
  885. ~~~~~~~~~~~~~~~~~~~~~
    
  886. 
    
  887. You can also retrieve information about any of the available languages using
    
  888. provided template tags and filters. To get information about a single language,
    
  889. use the ``{% get_language_info %}`` tag::
    
  890. 
    
  891.     {% get_language_info for LANGUAGE_CODE as lang %}
    
  892.     {% get_language_info for "pl" as lang %}
    
  893. 
    
  894. You can then access the information::
    
  895. 
    
  896.     Language code: {{ lang.code }}<br>
    
  897.     Name of language: {{ lang.name_local }}<br>
    
  898.     Name in English: {{ lang.name }}<br>
    
  899.     Bi-directional: {{ lang.bidi }}
    
  900.     Name in the active language: {{ lang.name_translated }}
    
  901. 
    
  902. .. templatetag:: get_language_info_list
    
  903. 
    
  904. ``get_language_info_list``
    
  905. ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  906. 
    
  907. You can also use the ``{% get_language_info_list %}`` template tag to retrieve
    
  908. information for a list of languages (e.g. active languages as specified in
    
  909. :setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
    
  910. view <set_language-redirect-view>` for an example of how to display a language
    
  911. selector using ``{% get_language_info_list %}``.
    
  912. 
    
  913. In addition to :setting:`LANGUAGES` style list of tuples,
    
  914. ``{% get_language_info_list %}`` supports lists of language codes.
    
  915. If you do this in your view:
    
  916. 
    
  917. .. code-block:: python
    
  918. 
    
  919.     context = {'available_languages': ['en', 'es', 'fr']}
    
  920.     return render(request, 'mytemplate.html', context)
    
  921. 
    
  922. you can iterate over those languages in the template::
    
  923. 
    
  924.   {% get_language_info_list for available_languages as langs %}
    
  925.   {% for lang in langs %} ... {% endfor %}
    
  926. 
    
  927. .. templatefilter:: language_name
    
  928. .. templatefilter:: language_name_local
    
  929. .. templatefilter:: language_bidi
    
  930. .. templatefilter:: language_name_translated
    
  931. 
    
  932. Template filters
    
  933. ~~~~~~~~~~~~~~~~
    
  934. 
    
  935. There are also some filters available for convenience:
    
  936. 
    
  937. * ``{{ LANGUAGE_CODE|language_name }}`` ("German")
    
  938. * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
    
  939. * ``{{ LANGUAGE_CODE|language_bidi }}`` (False)
    
  940. * ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active language is Czech)
    
  941. 
    
  942. Internationalization: in JavaScript code
    
  943. ========================================
    
  944. 
    
  945. .. highlight:: python
    
  946. 
    
  947. Adding translations to JavaScript poses some problems:
    
  948. 
    
  949. * JavaScript code doesn't have access to a ``gettext`` implementation.
    
  950. 
    
  951. * JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to
    
  952.   be delivered by the server.
    
  953. 
    
  954. * The translation catalogs for JavaScript should be kept as small as
    
  955.   possible.
    
  956. 
    
  957. Django provides an integrated solution for these problems: It passes the
    
  958. translations into JavaScript, so you can call ``gettext``, etc., from within
    
  959. JavaScript.
    
  960. 
    
  961. The main solution to these problems is the following ``JavaScriptCatalog`` view,
    
  962. which generates a JavaScript code library with functions that mimic the
    
  963. ``gettext`` interface, plus an array of translation strings.
    
  964. 
    
  965. The ``JavaScriptCatalog`` view
    
  966. ------------------------------
    
  967. 
    
  968. .. module:: django.views.i18n
    
  969. 
    
  970. .. class:: JavaScriptCatalog
    
  971. 
    
  972.     A view that produces a JavaScript code library with functions that mimic
    
  973.     the ``gettext`` interface, plus an array of translation strings.
    
  974. 
    
  975.     **Attributes**
    
  976. 
    
  977.     .. attribute:: domain
    
  978. 
    
  979.         Translation domain containing strings to add in the view output.
    
  980.         Defaults to ``'djangojs'``.
    
  981. 
    
  982.     .. attribute:: packages
    
  983. 
    
  984.         A list of :attr:`application names <django.apps.AppConfig.name>` among
    
  985.         installed applications. Those apps should contain a ``locale``
    
  986.         directory. All those catalogs plus all catalogs found in
    
  987.         :setting:`LOCALE_PATHS` (which are always included) are merged into one
    
  988.         catalog. Defaults to ``None``, which means that all available
    
  989.         translations from all :setting:`INSTALLED_APPS` are provided in the
    
  990.         JavaScript output.
    
  991. 
    
  992.     **Example with default values**::
    
  993. 
    
  994.         from django.views.i18n import JavaScriptCatalog
    
  995. 
    
  996.         urlpatterns = [
    
  997.             path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
    
  998.         ]
    
  999. 
    
  1000.     **Example with custom packages**::
    
  1001. 
    
  1002.         urlpatterns = [
    
  1003.             path('jsi18n/myapp/',
    
  1004.                  JavaScriptCatalog.as_view(packages=['your.app.label']),
    
  1005.                  name='javascript-catalog'),
    
  1006.         ]
    
  1007. 
    
  1008.     If your root URLconf uses :func:`~django.conf.urls.i18n.i18n_patterns`,
    
  1009.     ``JavaScriptCatalog`` must also be wrapped by ``i18n_patterns()`` for the
    
  1010.     catalog to be correctly generated.
    
  1011. 
    
  1012.     **Example with** ``i18n_patterns()``::
    
  1013. 
    
  1014.         from django.conf.urls.i18n import i18n_patterns
    
  1015. 
    
  1016.         urlpatterns = i18n_patterns(
    
  1017.             path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
    
  1018.         )
    
  1019. 
    
  1020. The precedence of translations is such that the packages appearing later in the
    
  1021. ``packages`` argument have higher precedence than the ones appearing at the
    
  1022. beginning. This is important in the case of clashing translations for the same
    
  1023. literal.
    
  1024. 
    
  1025. If you use more than one ``JavaScriptCatalog`` view on a site and some of them
    
  1026. define the same strings, the strings in the catalog that was loaded last take
    
  1027. precedence.
    
  1028. 
    
  1029. Using the JavaScript translation catalog
    
  1030. ----------------------------------------
    
  1031. 
    
  1032. .. highlight:: javascript
    
  1033. 
    
  1034. To use the catalog, pull in the dynamically generated script like this:
    
  1035. 
    
  1036. .. code-block:: html+django
    
  1037. 
    
  1038.     <script src="{% url 'javascript-catalog' %}"></script>
    
  1039. 
    
  1040. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
    
  1041. When the catalog is loaded, your JavaScript code can use the following methods:
    
  1042. 
    
  1043. * ``gettext``
    
  1044. * ``ngettext``
    
  1045. * ``interpolate``
    
  1046. * ``get_format``
    
  1047. * ``gettext_noop``
    
  1048. * ``pgettext``
    
  1049. * ``npgettext``
    
  1050. * ``pluralidx``
    
  1051. 
    
  1052. ``gettext``
    
  1053. ~~~~~~~~~~~
    
  1054. 
    
  1055. The ``gettext`` function behaves similarly to the standard ``gettext``
    
  1056. interface within your Python code::
    
  1057. 
    
  1058.     document.write(gettext('this is to be translated'));
    
  1059. 
    
  1060. ``ngettext``
    
  1061. ~~~~~~~~~~~~
    
  1062. 
    
  1063. The ``ngettext`` function provides an interface to pluralize words and
    
  1064. phrases::
    
  1065. 
    
  1066.     const objectCount = 1 // or 0, or 2, or 3, ...
    
  1067.     const string = ngettext(
    
  1068.         'literal for the singular case',
    
  1069.         'literal for the plural case',
    
  1070.         objectCount
    
  1071.     );
    
  1072. 
    
  1073. ``interpolate``
    
  1074. ~~~~~~~~~~~~~~~
    
  1075. 
    
  1076. The ``interpolate`` function supports dynamically populating a format string.
    
  1077. The interpolation syntax is borrowed from Python, so the ``interpolate``
    
  1078. function supports both positional and named interpolation:
    
  1079. 
    
  1080. * Positional interpolation: ``obj`` contains a JavaScript Array object
    
  1081.   whose elements values are then sequentially interpolated in their
    
  1082.   corresponding ``fmt`` placeholders in the same order they appear.
    
  1083.   For example::
    
  1084. 
    
  1085.     const formats = ngettext(
    
  1086.       'There is %s object. Remaining: %s',
    
  1087.       'There are %s objects. Remaining: %s',
    
  1088.       11
    
  1089.     );
    
  1090.     const string = interpolate(formats, [11, 20]);
    
  1091.     // string is 'There are 11 objects. Remaining: 20'
    
  1092. 
    
  1093. * Named interpolation: This mode is selected by passing the optional
    
  1094.   boolean ``named`` parameter as ``true``. ``obj`` contains a JavaScript
    
  1095.   object or associative array. For example::
    
  1096. 
    
  1097.     const data = {
    
  1098.       count: 10,
    
  1099.       total: 50
    
  1100.     };
    
  1101. 
    
  1102.     const formats = ngettext(
    
  1103.         'Total: %(total)s, there is %(count)s object',
    
  1104.         'there are %(count)s of a total of %(total)s objects',
    
  1105.         data.count
    
  1106.     );
    
  1107.     const string = interpolate(formats, data, true);
    
  1108. 
    
  1109. You shouldn't go over the top with string interpolation, though: this is still
    
  1110. JavaScript, so the code has to make repeated regular-expression substitutions.
    
  1111. This isn't as fast as string interpolation in Python, so keep it to those
    
  1112. cases where you really need it (for example, in conjunction with ``ngettext``
    
  1113. to produce proper pluralizations).
    
  1114. 
    
  1115. ``get_format``
    
  1116. ~~~~~~~~~~~~~~
    
  1117. 
    
  1118. The ``get_format`` function has access to the configured i18n formatting
    
  1119. settings and can retrieve the format string for a given setting name::
    
  1120. 
    
  1121.     document.write(get_format('DATE_FORMAT'));
    
  1122.     // 'N j, Y'
    
  1123. 
    
  1124. It has access to the following settings:
    
  1125. 
    
  1126. * :setting:`DATE_FORMAT`
    
  1127. * :setting:`DATE_INPUT_FORMATS`
    
  1128. * :setting:`DATETIME_FORMAT`
    
  1129. * :setting:`DATETIME_INPUT_FORMATS`
    
  1130. * :setting:`DECIMAL_SEPARATOR`
    
  1131. * :setting:`FIRST_DAY_OF_WEEK`
    
  1132. * :setting:`MONTH_DAY_FORMAT`
    
  1133. * :setting:`NUMBER_GROUPING`
    
  1134. * :setting:`SHORT_DATE_FORMAT`
    
  1135. * :setting:`SHORT_DATETIME_FORMAT`
    
  1136. * :setting:`THOUSAND_SEPARATOR`
    
  1137. * :setting:`TIME_FORMAT`
    
  1138. * :setting:`TIME_INPUT_FORMATS`
    
  1139. * :setting:`YEAR_MONTH_FORMAT`
    
  1140. 
    
  1141. This is useful for maintaining formatting consistency with the Python-rendered
    
  1142. values.
    
  1143. 
    
  1144. ``gettext_noop``
    
  1145. ~~~~~~~~~~~~~~~~
    
  1146. 
    
  1147. This emulates the ``gettext`` function but does nothing, returning whatever
    
  1148. is passed to it::
    
  1149. 
    
  1150.     document.write(gettext_noop('this will not be translated'));
    
  1151. 
    
  1152. This is useful for stubbing out portions of the code that will need translation
    
  1153. in the future.
    
  1154. 
    
  1155. ``pgettext``
    
  1156. ~~~~~~~~~~~~
    
  1157. 
    
  1158. The ``pgettext`` function behaves like the Python variant
    
  1159. (:func:`~django.utils.translation.pgettext()`), providing a contextually
    
  1160. translated word::
    
  1161. 
    
  1162.     document.write(pgettext('month name', 'May'));
    
  1163. 
    
  1164. ``npgettext``
    
  1165. ~~~~~~~~~~~~~
    
  1166. 
    
  1167. The ``npgettext`` function also behaves like the Python variant
    
  1168. (:func:`~django.utils.translation.npgettext()`), providing a **pluralized**
    
  1169. contextually translated word::
    
  1170. 
    
  1171.     document.write(npgettext('group', 'party', 1));
    
  1172.     // party
    
  1173.     document.write(npgettext('group', 'party', 2));
    
  1174.     // parties
    
  1175. 
    
  1176. ``pluralidx``
    
  1177. ~~~~~~~~~~~~~
    
  1178. 
    
  1179. The ``pluralidx`` function works in a similar way to the :tfilter:`pluralize`
    
  1180. template filter, determining if a given ``count`` should use a plural form of
    
  1181. a word or not::
    
  1182. 
    
  1183.     document.write(pluralidx(0));
    
  1184.     // true
    
  1185.     document.write(pluralidx(1));
    
  1186.     // false
    
  1187.     document.write(pluralidx(2));
    
  1188.     // true
    
  1189. 
    
  1190. In the simplest case, if no custom pluralization is needed, this returns
    
  1191. ``false`` for the integer ``1`` and ``true`` for all other numbers.
    
  1192. 
    
  1193. However, pluralization is not this simple in all languages. If the language does
    
  1194. not support pluralization, an empty value is provided.
    
  1195. 
    
  1196. Additionally, if there are complex rules around pluralization, the catalog view
    
  1197. will render a conditional expression. This will evaluate to either a ``true``
    
  1198. (should pluralize) or ``false`` (should **not** pluralize) value.
    
  1199. 
    
  1200. .. highlight:: python
    
  1201. 
    
  1202. The ``JSONCatalog`` view
    
  1203. ------------------------
    
  1204. 
    
  1205. .. class:: JSONCatalog
    
  1206. 
    
  1207.     In order to use another client-side library to handle translations, you may
    
  1208.     want to take advantage of the ``JSONCatalog`` view. It's similar to
    
  1209.     :class:`~django.views.i18n.JavaScriptCatalog` but returns a JSON response.
    
  1210. 
    
  1211.     See the documentation for :class:`~django.views.i18n.JavaScriptCatalog`
    
  1212.     to learn about possible values and use of the ``domain`` and ``packages``
    
  1213.     attributes.
    
  1214. 
    
  1215.     The response format is as follows:
    
  1216. 
    
  1217.     .. code-block:: text
    
  1218. 
    
  1219.         {
    
  1220.             "catalog": {
    
  1221.                 # Translations catalog
    
  1222.             },
    
  1223.             "formats": {
    
  1224.                 # Language formats for date, time, etc.
    
  1225.             },
    
  1226.             "plural": "..."  # Expression for plural forms, or null.
    
  1227.         }
    
  1228. 
    
  1229.     .. JSON doesn't allow comments so highlighting as JSON won't work here.
    
  1230. 
    
  1231. Note on performance
    
  1232. -------------------
    
  1233. 
    
  1234. The various JavaScript/JSON i18n views generate the catalog from ``.mo`` files
    
  1235. on every request. Since its output is constant, at least for a given version
    
  1236. of a site, it's a good candidate for caching.
    
  1237. 
    
  1238. Server-side caching will reduce CPU load. It's easily implemented with the
    
  1239. :func:`~django.views.decorators.cache.cache_page` decorator. To trigger cache
    
  1240. invalidation when your translations change, provide a version-dependent key
    
  1241. prefix, as shown in the example below, or map the view at a version-dependent
    
  1242. URL::
    
  1243. 
    
  1244.     from django.views.decorators.cache import cache_page
    
  1245.     from django.views.i18n import JavaScriptCatalog
    
  1246. 
    
  1247.     # The value returned by get_version() must change when translations change.
    
  1248.     urlpatterns = [
    
  1249.         path('jsi18n/',
    
  1250.              cache_page(86400, key_prefix='jsi18n-%s' % get_version())(JavaScriptCatalog.as_view()),
    
  1251.              name='javascript-catalog'),
    
  1252.     ]
    
  1253. 
    
  1254. Client-side caching will save bandwidth and make your site load faster. If
    
  1255. you're using ETags (:class:`~django.middleware.http.ConditionalGetMiddleware`),
    
  1256. you're already covered. Otherwise, you can apply :ref:`conditional decorators
    
  1257. <conditional-decorators>`. In the following example, the cache is invalidated
    
  1258. whenever you restart your application server::
    
  1259. 
    
  1260.     from django.utils import timezone
    
  1261.     from django.views.decorators.http import last_modified
    
  1262.     from django.views.i18n import JavaScriptCatalog
    
  1263. 
    
  1264.     last_modified_date = timezone.now()
    
  1265. 
    
  1266.     urlpatterns = [
    
  1267.         path('jsi18n/',
    
  1268.              last_modified(lambda req, **kw: last_modified_date)(JavaScriptCatalog.as_view()),
    
  1269.              name='javascript-catalog'),
    
  1270.     ]
    
  1271. 
    
  1272. You can even pre-generate the JavaScript catalog as part of your deployment
    
  1273. procedure and serve it as a static file. This radical technique is implemented
    
  1274. in django-statici18n_.
    
  1275. 
    
  1276. .. _django-statici18n: https://django-statici18n.readthedocs.io/
    
  1277. 
    
  1278. .. _url-internationalization:
    
  1279. 
    
  1280. Internationalization: in URL patterns
    
  1281. =====================================
    
  1282. 
    
  1283. .. module:: django.conf.urls.i18n
    
  1284. 
    
  1285. Django provides two mechanisms to internationalize URL patterns:
    
  1286. 
    
  1287. * Adding the language prefix to the root of the URL patterns to make it
    
  1288.   possible for :class:`~django.middleware.locale.LocaleMiddleware` to detect
    
  1289.   the language to activate from the requested URL.
    
  1290. 
    
  1291. * Making URL patterns themselves translatable via the
    
  1292.   :func:`django.utils.translation.gettext_lazy()` function.
    
  1293. 
    
  1294. .. warning::
    
  1295. 
    
  1296.     Using either one of these features requires that an active language be set
    
  1297.     for each request; in other words, you need to have
    
  1298.     :class:`django.middleware.locale.LocaleMiddleware` in your
    
  1299.     :setting:`MIDDLEWARE` setting.
    
  1300. 
    
  1301. Language prefix in URL patterns
    
  1302. -------------------------------
    
  1303. 
    
  1304. .. function:: i18n_patterns(*urls, prefix_default_language=True)
    
  1305. 
    
  1306. This function can be used in a root URLconf and Django will automatically
    
  1307. prepend the current active language code to all URL patterns defined within
    
  1308. :func:`~django.conf.urls.i18n.i18n_patterns`.
    
  1309. 
    
  1310. Setting ``prefix_default_language`` to ``False`` removes the prefix from the
    
  1311. default language (:setting:`LANGUAGE_CODE`). This can be useful when adding
    
  1312. translations to existing site so that the current URLs won't change.
    
  1313. 
    
  1314. Example URL patterns::
    
  1315. 
    
  1316.     from django.conf.urls.i18n import i18n_patterns
    
  1317.     from django.urls import include, path
    
  1318. 
    
  1319.     from about import views as about_views
    
  1320.     from news import views as news_views
    
  1321.     from sitemap.views import sitemap
    
  1322. 
    
  1323.     urlpatterns = [
    
  1324.         path('sitemap.xml', sitemap, name='sitemap-xml'),
    
  1325.     ]
    
  1326. 
    
  1327.     news_patterns = ([
    
  1328.         path('', news_views.index, name='index'),
    
  1329.         path('category/<slug:slug>/', news_views.category, name='category'),
    
  1330.         path('<slug:slug>/', news_views.details, name='detail'),
    
  1331.     ], 'news')
    
  1332. 
    
  1333.     urlpatterns += i18n_patterns(
    
  1334.         path('about/', about_views.main, name='about'),
    
  1335.         path('news/', include(news_patterns, namespace='news')),
    
  1336.     )
    
  1337. 
    
  1338. After defining these URL patterns, Django will automatically add the
    
  1339. language prefix to the URL patterns that were added by the ``i18n_patterns``
    
  1340. function. Example::
    
  1341. 
    
  1342.     >>> from django.urls import reverse
    
  1343.     >>> from django.utils.translation import activate
    
  1344. 
    
  1345.     >>> activate('en')
    
  1346.     >>> reverse('sitemap-xml')
    
  1347.     '/sitemap.xml'
    
  1348.     >>> reverse('news:index')
    
  1349.     '/en/news/'
    
  1350. 
    
  1351.     >>> activate('nl')
    
  1352.     >>> reverse('news:detail', kwargs={'slug': 'news-slug'})
    
  1353.     '/nl/news/news-slug/'
    
  1354. 
    
  1355. With ``prefix_default_language=False`` and  ``LANGUAGE_CODE='en'``, the URLs
    
  1356. will be::
    
  1357. 
    
  1358.     >>> activate('en')
    
  1359.     >>> reverse('news:index')
    
  1360.     '/news/'
    
  1361. 
    
  1362.     >>> activate('nl')
    
  1363.     >>> reverse('news:index')
    
  1364.     '/nl/news/'
    
  1365. 
    
  1366. .. warning::
    
  1367. 
    
  1368.     :func:`~django.conf.urls.i18n.i18n_patterns` is only allowed in a root
    
  1369.     URLconf. Using it within an included URLconf will throw an
    
  1370.     :exc:`~django.core.exceptions.ImproperlyConfigured` exception.
    
  1371. 
    
  1372. .. warning::
    
  1373. 
    
  1374.     Ensure that you don't have non-prefixed URL patterns that might collide
    
  1375.     with an automatically-added language prefix.
    
  1376. 
    
  1377. .. _translating-urlpatterns:
    
  1378. 
    
  1379. Translating URL patterns
    
  1380. ------------------------
    
  1381. 
    
  1382. URL patterns can also be marked translatable using the
    
  1383. :func:`~django.utils.translation.gettext_lazy` function. Example::
    
  1384. 
    
  1385.     from django.conf.urls.i18n import i18n_patterns
    
  1386.     from django.urls import include, path
    
  1387.     from django.utils.translation import gettext_lazy as _
    
  1388. 
    
  1389.     from about import views as about_views
    
  1390.     from news import views as news_views
    
  1391.     from sitemaps.views import sitemap
    
  1392. 
    
  1393.     urlpatterns = [
    
  1394.         path('sitemap.xml', sitemap, name='sitemap-xml'),
    
  1395.     ]
    
  1396. 
    
  1397.     news_patterns = ([
    
  1398.         path('', news_views.index, name='index'),
    
  1399.         path(_('category/<slug:slug>/'), news_views.category, name='category'),
    
  1400.         path('<slug:slug>/', news_views.details, name='detail'),
    
  1401.     ], 'news')
    
  1402. 
    
  1403.     urlpatterns += i18n_patterns(
    
  1404.         path(_('about/'), about_views.main, name='about'),
    
  1405.         path(_('news/'), include(news_patterns, namespace='news')),
    
  1406.     )
    
  1407. 
    
  1408. After you've created the translations, the :func:`~django.urls.reverse`
    
  1409. function will return the URL in the active language. Example::
    
  1410. 
    
  1411.     >>> from django.urls import reverse
    
  1412.     >>> from django.utils.translation import activate
    
  1413. 
    
  1414.     >>> activate('en')
    
  1415.     >>> reverse('news:category', kwargs={'slug': 'recent'})
    
  1416.     '/en/news/category/recent/'
    
  1417. 
    
  1418.     >>> activate('nl')
    
  1419.     >>> reverse('news:category', kwargs={'slug': 'recent'})
    
  1420.     '/nl/nieuws/categorie/recent/'
    
  1421. 
    
  1422. .. warning::
    
  1423. 
    
  1424.     In most cases, it's best to use translated URLs only within a language code
    
  1425.     prefixed block of patterns (using
    
  1426.     :func:`~django.conf.urls.i18n.i18n_patterns`), to avoid the possibility
    
  1427.     that a carelessly translated URL causes a collision with a non-translated
    
  1428.     URL pattern.
    
  1429. 
    
  1430. .. _reversing_in_templates:
    
  1431. 
    
  1432. Reversing in templates
    
  1433. ----------------------
    
  1434. 
    
  1435. If localized URLs get reversed in templates they always use the current
    
  1436. language. To link to a URL in another language use the :ttag:`language`
    
  1437. template tag. It enables the given language in the enclosed template section:
    
  1438. 
    
  1439. .. code-block:: html+django
    
  1440. 
    
  1441.     {% load i18n %}
    
  1442. 
    
  1443.     {% get_available_languages as languages %}
    
  1444. 
    
  1445.     {% translate "View this category in:" %}
    
  1446.     {% for lang_code, lang_name in languages %}
    
  1447.         {% language lang_code %}
    
  1448.         <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
    
  1449.         {% endlanguage %}
    
  1450.     {% endfor %}
    
  1451. 
    
  1452. The :ttag:`language` tag expects the language code as the only argument.
    
  1453. 
    
  1454. .. _how-to-create-language-files:
    
  1455. 
    
  1456. Localization: how to create language files
    
  1457. ==========================================
    
  1458. 
    
  1459. Once the string literals of an application have been tagged for later
    
  1460. translation, the translation themselves need to be written (or obtained). Here's
    
  1461. how that works.
    
  1462. 
    
  1463. Message files
    
  1464. -------------
    
  1465. 
    
  1466. The first step is to create a :term:`message file` for a new language. A message
    
  1467. file is a plain-text file, representing a single language, that contains all
    
  1468. available translation strings and how they should be represented in the given
    
  1469. language. Message files have a ``.po`` file extension.
    
  1470. 
    
  1471. Django comes with a tool, :djadmin:`django-admin makemessages
    
  1472. <makemessages>`, that automates the creation and upkeep of these files.
    
  1473. 
    
  1474. .. admonition:: Gettext utilities
    
  1475. 
    
  1476.     The ``makemessages`` command (and ``compilemessages`` discussed later) use
    
  1477.     commands from the GNU gettext toolset: ``xgettext``, ``msgfmt``,
    
  1478.     ``msgmerge`` and ``msguniq``.
    
  1479. 
    
  1480.     The minimum version of the ``gettext`` utilities supported is 0.15.
    
  1481. 
    
  1482. To create or update a message file, run this command::
    
  1483. 
    
  1484.     django-admin makemessages -l de
    
  1485. 
    
  1486. ...where ``de`` is the :term:`locale name` for the message file you want to
    
  1487. create. For example, ``pt_BR`` for Brazilian Portuguese, ``de_AT`` for Austrian
    
  1488. German or ``id`` for Indonesian.
    
  1489. 
    
  1490. The script should be run from one of two places:
    
  1491. 
    
  1492. * The root directory of your Django project (the one that contains
    
  1493.   ``manage.py``).
    
  1494. * The root directory of one of your Django apps.
    
  1495. 
    
  1496. The script runs over your project source tree or your application source tree
    
  1497. and pulls out all strings marked for translation (see
    
  1498. :ref:`how-django-discovers-translations` and be sure :setting:`LOCALE_PATHS`
    
  1499. is configured correctly). It creates (or updates) a message file in the
    
  1500. directory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the file will be
    
  1501. ``locale/de/LC_MESSAGES/django.po``.
    
  1502. 
    
  1503. When you run ``makemessages`` from the root directory of your project, the
    
  1504. extracted strings will be automatically distributed to the proper message files.
    
  1505. That is, a string extracted from a file of an app containing a ``locale``
    
  1506. directory will go in a message file under that directory. A string extracted
    
  1507. from a file of an app without any ``locale`` directory will either go in a
    
  1508. message file under the directory listed first in :setting:`LOCALE_PATHS` or
    
  1509. will generate an error if :setting:`LOCALE_PATHS` is empty.
    
  1510. 
    
  1511. By default :djadmin:`django-admin makemessages <makemessages>` examines every
    
  1512. file that has the ``.html``, ``.txt`` or ``.py`` file extension. If you want to
    
  1513. override that default, use the :option:`--extension <makemessages --extension>`
    
  1514. or ``-e`` option to specify the file extensions to examine::
    
  1515. 
    
  1516.     django-admin makemessages -l de -e txt
    
  1517. 
    
  1518. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
    
  1519. multiple times::
    
  1520. 
    
  1521.     django-admin makemessages -l de -e html,txt -e xml
    
  1522. 
    
  1523. .. warning::
    
  1524. 
    
  1525.     When :ref:`creating message files from JavaScript source code
    
  1526.     <creating-message-files-from-js-code>` you need to use the special
    
  1527.     ``djangojs`` domain, **not** ``-e js``.
    
  1528. 
    
  1529. .. admonition:: Using Jinja2 templates?
    
  1530. 
    
  1531.     :djadmin:`makemessages` doesn't understand the syntax of Jinja2 templates.
    
  1532.     To extract strings from a project containing Jinja2 templates, use `Message
    
  1533.     Extracting`_ from Babel_ instead.
    
  1534. 
    
  1535.     Here's an example ``babel.cfg`` configuration file::
    
  1536. 
    
  1537.         # Extraction from Python source files
    
  1538.         [python: **.py]
    
  1539. 
    
  1540.         # Extraction from Jinja2 templates
    
  1541.         [jinja2: **.jinja]
    
  1542.         extensions = jinja2.ext.with_
    
  1543. 
    
  1544.     Make sure you list all extensions you're using! Otherwise Babel won't
    
  1545.     recognize the tags defined by these extensions and will ignore Jinja2
    
  1546.     templates containing them entirely.
    
  1547. 
    
  1548.     Babel provides similar features to :djadmin:`makemessages`, can replace it
    
  1549.     in general, and doesn't depend on ``gettext``. For more information, read
    
  1550.     its documentation about `working with message catalogs`_.
    
  1551. 
    
  1552.     .. _Message extracting: https://babel.pocoo.org/en/latest/messages.html#message-extraction
    
  1553.     .. _Babel: https://babel.pocoo.org/en/latest/
    
  1554.     .. _working with message catalogs: https://babel.pocoo.org/en/latest/messages.html
    
  1555. 
    
  1556. .. admonition:: No gettext?
    
  1557. 
    
  1558.     If you don't have the ``gettext`` utilities installed,
    
  1559.     :djadmin:`makemessages` will create empty files. If that's the case, either
    
  1560.     install the ``gettext`` utilities or copy the English message file
    
  1561.     (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
    
  1562.     point, which is an empty translation file.
    
  1563. 
    
  1564. .. admonition:: Working on Windows?
    
  1565. 
    
  1566.    If you're using Windows and need to install the GNU gettext utilities so
    
  1567.    :djadmin:`makemessages` works, see :ref:`gettext_on_windows` for more
    
  1568.    information.
    
  1569. 
    
  1570. Each ``.po`` file contains a small bit of metadata, such as the translation
    
  1571. maintainer's contact information, but the bulk of the file is a list of
    
  1572. **messages** -- mappings between translation strings and the actual translated
    
  1573. text for the particular language.
    
  1574. 
    
  1575. For example, if your Django app contained a translation string for the text
    
  1576. ``"Welcome to my site."``, like so::
    
  1577. 
    
  1578.     _("Welcome to my site.")
    
  1579. 
    
  1580. ...then :djadmin:`django-admin makemessages <makemessages>` will have created
    
  1581. a ``.po`` file containing the following snippet -- a message:
    
  1582. 
    
  1583. .. code-block:: po
    
  1584. 
    
  1585.     #: path/to/python/module.py:23
    
  1586.     msgid "Welcome to my site."
    
  1587.     msgstr ""
    
  1588. 
    
  1589. A quick explanation:
    
  1590. 
    
  1591. * ``msgid`` is the translation string, which appears in the source. Don't
    
  1592.   change it.
    
  1593. * ``msgstr`` is where you put the language-specific translation. It starts
    
  1594.   out empty, so it's your responsibility to change it. Make sure you keep
    
  1595.   the quotes around your translation.
    
  1596. * As a convenience, each message includes, in the form of a comment line
    
  1597.   prefixed with ``#`` and located above the ``msgid`` line, the filename and
    
  1598.   line number from which the translation string was gleaned.
    
  1599. 
    
  1600. Long messages are a special case. There, the first string directly after the
    
  1601. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
    
  1602. written over the next few lines as one string per line. Those strings are
    
  1603. directly concatenated. Don't forget trailing spaces within the strings;
    
  1604. otherwise, they'll be tacked together without whitespace!
    
  1605. 
    
  1606. .. admonition:: Mind your charset
    
  1607. 
    
  1608.     Due to the way the ``gettext`` tools work internally and because we want to
    
  1609.     allow non-ASCII source strings in Django's core and your applications, you
    
  1610.     **must** use UTF-8 as the encoding for your ``.po`` files (the default when
    
  1611.     ``.po`` files are created).  This means that everybody will be using the
    
  1612.     same encoding, which is important when Django processes the ``.po`` files.
    
  1613. 
    
  1614. .. admonition:: Fuzzy entries
    
  1615. 
    
  1616.     :djadmin:`makemessages` sometimes generates translation entries marked as
    
  1617.     fuzzy, e.g. when translations are inferred from previously translated
    
  1618.     strings. By default, fuzzy entries are **not** processed by
    
  1619.     :djadmin:`compilemessages`.
    
  1620. 
    
  1621. To reexamine all source code and templates for new translation strings and
    
  1622. update all message files for **all** languages, run this::
    
  1623. 
    
  1624.     django-admin makemessages -a
    
  1625. 
    
  1626. Compiling message files
    
  1627. -----------------------
    
  1628. 
    
  1629. After you create your message file -- and each time you make changes to it --
    
  1630. you'll need to compile it into a more efficient form, for use by ``gettext``. Do
    
  1631. this with the :djadmin:`django-admin compilemessages <compilemessages>`
    
  1632. utility.
    
  1633. 
    
  1634. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
    
  1635. are binary files optimized for use by ``gettext``. In the same directory from
    
  1636. which you ran :djadmin:`django-admin makemessages <makemessages>`, run
    
  1637. :djadmin:`django-admin compilemessages <compilemessages>` like this::
    
  1638. 
    
  1639.    django-admin compilemessages
    
  1640. 
    
  1641. That's it. Your translations are ready for use.
    
  1642. 
    
  1643. .. admonition:: Working on Windows?
    
  1644. 
    
  1645.    If you're using Windows and need to install the GNU gettext utilities so
    
  1646.    :djadmin:`django-admin compilemessages <compilemessages>` works see
    
  1647.    :ref:`gettext_on_windows` for more information.
    
  1648. 
    
  1649. .. admonition:: ``.po`` files: Encoding and BOM usage.
    
  1650. 
    
  1651.    Django only supports ``.po`` files encoded in UTF-8 and without any BOM
    
  1652.    (Byte Order Mark) so if your text editor adds such marks to the beginning of
    
  1653.    files by default then you will need to reconfigure it.
    
  1654. 
    
  1655. Troubleshooting: ``gettext()`` incorrectly detects ``python-format`` in strings with percent signs
    
  1656. --------------------------------------------------------------------------------------------------
    
  1657. 
    
  1658. In some cases, such as strings with a percent sign followed by a space and a
    
  1659. :ref:`string conversion type <old-string-formatting>` (e.g.
    
  1660. ``_("10% interest")``), :func:`~django.utils.translation.gettext` incorrectly
    
  1661. flags strings with ``python-format``.
    
  1662. 
    
  1663. If you try to compile message files with incorrectly flagged strings, you'll
    
  1664. get an error message like ``number of format specifications in 'msgid' and
    
  1665. 'msgstr' does not match`` or ``'msgstr' is not a valid Python format string,
    
  1666. unlike 'msgid'``.
    
  1667. 
    
  1668. To workaround this, you can escape percent signs by adding a second percent
    
  1669. sign::
    
  1670. 
    
  1671.     from django.utils.translation import gettext as _
    
  1672.     output = _("10%% interest")
    
  1673. 
    
  1674. Or you can use ``no-python-format`` so that all percent signs are treated as
    
  1675. literals::
    
  1676. 
    
  1677.     # xgettext:no-python-format
    
  1678.     output = _("10% interest")
    
  1679. 
    
  1680. .. _creating-message-files-from-js-code:
    
  1681. 
    
  1682. Creating message files from JavaScript source code
    
  1683. --------------------------------------------------
    
  1684. 
    
  1685. You create and update the message files the same way as the other Django message
    
  1686. files -- with the :djadmin:`django-admin makemessages <makemessages>` tool.
    
  1687. The only difference is you need to explicitly specify what in gettext parlance
    
  1688. is known as a domain in this case the ``djangojs`` domain, by providing a ``-d
    
  1689. djangojs`` parameter, like this::
    
  1690. 
    
  1691.     django-admin makemessages -d djangojs -l de
    
  1692. 
    
  1693. This would create or update the message file for JavaScript for German. After
    
  1694. updating message files, run :djadmin:`django-admin compilemessages
    
  1695. <compilemessages>` the same way as you do with normal Django message files.
    
  1696. 
    
  1697. .. _gettext_on_windows:
    
  1698. 
    
  1699. ``gettext`` on Windows
    
  1700. ----------------------
    
  1701. 
    
  1702. This is only needed for people who either want to extract message IDs or compile
    
  1703. message files (``.po``). Translation work itself involves editing existing
    
  1704. files of this type, but if you want to create your own message files, or want
    
  1705. to test or compile a changed message file, download `a precompiled binary
    
  1706. installer <https://mlocati.github.io/articles/gettext-iconv-windows.html>`_.
    
  1707. 
    
  1708. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
    
  1709. the ``xgettext --version`` command works properly. Do not attempt to use Django
    
  1710. translation utilities with a ``gettext`` package if the command ``xgettext
    
  1711. --version`` entered at a Windows command prompt causes a popup window saying
    
  1712. "``xgettext.exe`` has generated errors and will be closed by Windows".
    
  1713. 
    
  1714. .. _customizing-makemessages:
    
  1715. 
    
  1716. Customizing the ``makemessages`` command
    
  1717. ----------------------------------------
    
  1718. 
    
  1719. If you want to pass additional parameters to ``xgettext``, you need to create a
    
  1720. custom :djadmin:`makemessages` command and override its ``xgettext_options``
    
  1721. attribute::
    
  1722. 
    
  1723.     from django.core.management.commands import makemessages
    
  1724. 
    
  1725.     class Command(makemessages.Command):
    
  1726.         xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']
    
  1727. 
    
  1728. If you need more flexibility, you could also add a new argument to your custom
    
  1729. :djadmin:`makemessages` command::
    
  1730. 
    
  1731.     from django.core.management.commands import makemessages
    
  1732. 
    
  1733.     class Command(makemessages.Command):
    
  1734. 
    
  1735.         def add_arguments(self, parser):
    
  1736.             super().add_arguments(parser)
    
  1737.             parser.add_argument(
    
  1738.                 '--extra-keyword',
    
  1739.                 dest='xgettext_keywords',
    
  1740.                 action='append',
    
  1741.             )
    
  1742. 
    
  1743.         def handle(self, *args, **options):
    
  1744.             xgettext_keywords = options.pop('xgettext_keywords')
    
  1745.             if xgettext_keywords:
    
  1746.                 self.xgettext_options = (
    
  1747.                     makemessages.Command.xgettext_options[:] +
    
  1748.                     ['--keyword=%s' % kwd for kwd in xgettext_keywords]
    
  1749.                 )
    
  1750.             super().handle(*args, **options)
    
  1751. 
    
  1752. Miscellaneous
    
  1753. =============
    
  1754. 
    
  1755. .. _set_language-redirect-view:
    
  1756. 
    
  1757. The ``set_language`` redirect view
    
  1758. ----------------------------------
    
  1759. 
    
  1760. .. currentmodule:: django.views.i18n
    
  1761. 
    
  1762. .. function:: set_language(request)
    
  1763. 
    
  1764. As a convenience, Django comes with a view, :func:`django.views.i18n.set_language`,
    
  1765. that sets a user's language preference and redirects to a given URL or, by default,
    
  1766. back to the previous page.
    
  1767. 
    
  1768. Activate this view by adding the following line to your URLconf::
    
  1769. 
    
  1770.     path('i18n/', include('django.conf.urls.i18n')),
    
  1771. 
    
  1772. (Note that this example makes the view available at ``/i18n/setlang/``.)
    
  1773. 
    
  1774. .. warning::
    
  1775. 
    
  1776.     Make sure that you don't include the above URL within
    
  1777.     :func:`~django.conf.urls.i18n.i18n_patterns` - it needs to be
    
  1778.     language-independent itself to work correctly.
    
  1779. 
    
  1780. The view expects to be called via the ``POST`` method, with a ``language``
    
  1781. parameter set in request. If session support is enabled, the view saves the
    
  1782. language choice in the user's session. It also saves the language choice in a
    
  1783. cookie that is named ``django_language`` by default. (The name can be changed
    
  1784. through the :setting:`LANGUAGE_COOKIE_NAME` setting.)
    
  1785. 
    
  1786. After setting the language choice, Django looks for a ``next`` parameter in the
    
  1787. ``POST`` or ``GET`` data. If that is found and Django considers it to be a safe
    
  1788. URL (i.e. it doesn't point to a different host and uses a safe scheme), a
    
  1789. redirect to that URL will be performed. Otherwise, Django may fall back to
    
  1790. redirecting the user to the URL from the ``Referer`` header or, if it is not
    
  1791. set, to ``/``, depending on the nature of the request:
    
  1792. 
    
  1793. * If the request accepts HTML content (based on its ``Accept`` HTTP header),
    
  1794.   the fallback will always be performed.
    
  1795. 
    
  1796. * If the request doesn't accept HTML, the fallback will be performed only if
    
  1797.   the ``next`` parameter was set. Otherwise a 204 status code (No Content) will
    
  1798.   be returned.
    
  1799. 
    
  1800. Here's example HTML template code:
    
  1801. 
    
  1802. .. code-block:: html+django
    
  1803. 
    
  1804.     {% load i18n %}
    
  1805. 
    
  1806.     <form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    
  1807.         <input name="next" type="hidden" value="{{ redirect_to }}">
    
  1808.         <select name="language">
    
  1809.             {% get_current_language as LANGUAGE_CODE %}
    
  1810.             {% get_available_languages as LANGUAGES %}
    
  1811.             {% get_language_info_list for LANGUAGES as languages %}
    
  1812.             {% for language in languages %}
    
  1813.                 <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
    
  1814.                     {{ language.name_local }} ({{ language.code }})
    
  1815.                 </option>
    
  1816.             {% endfor %}
    
  1817.         </select>
    
  1818.         <input type="submit" value="Go">
    
  1819.     </form>
    
  1820. 
    
  1821. In this example, Django looks up the URL of the page to which the user will be
    
  1822. redirected in the ``redirect_to`` context variable.
    
  1823. 
    
  1824. .. _explicitly-setting-the-active-language:
    
  1825. 
    
  1826. Explicitly setting the active language
    
  1827. --------------------------------------
    
  1828. 
    
  1829. .. highlight:: python
    
  1830. 
    
  1831. You may want to set the active language for the current session explicitly. Perhaps
    
  1832. a user's language preference is retrieved from another system, for example.
    
  1833. You've already been introduced to :func:`django.utils.translation.activate()`. That
    
  1834. applies to the current thread only. To persist the language for the entire
    
  1835. session in a cookie, set the :setting:`LANGUAGE_COOKIE_NAME` cookie on the
    
  1836. response::
    
  1837. 
    
  1838.     from django.conf import settings
    
  1839.     from django.http import HttpResponse
    
  1840.     from django.utils import translation
    
  1841.     user_language = 'fr'
    
  1842.     translation.activate(user_language)
    
  1843.     response = HttpResponse(...)
    
  1844.     response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
    
  1845. 
    
  1846. You would typically want to use both: :func:`django.utils.translation.activate()`
    
  1847. changes the language for this thread, and setting the cookie makes this
    
  1848. preference persist in future requests.
    
  1849. 
    
  1850. Using translations outside views and templates
    
  1851. ----------------------------------------------
    
  1852. 
    
  1853. While Django provides a rich set of i18n tools for use in views and templates,
    
  1854. it does not restrict the usage to Django-specific code. The Django translation
    
  1855. mechanisms can be used to translate arbitrary texts to any language that is
    
  1856. supported by Django (as long as an appropriate translation catalog exists, of
    
  1857. course). You can load a translation catalog, activate it and translate text to
    
  1858. language of your choice, but remember to switch back to original language, as
    
  1859. activating a translation catalog is done on per-thread basis and such change
    
  1860. will affect code running in the same thread.
    
  1861. 
    
  1862. For example::
    
  1863. 
    
  1864.     from django.utils import translation
    
  1865. 
    
  1866.     def welcome_translated(language):
    
  1867.         cur_language = translation.get_language()
    
  1868.         try:
    
  1869.             translation.activate(language)
    
  1870.             text = translation.gettext('welcome')
    
  1871.         finally:
    
  1872.             translation.activate(cur_language)
    
  1873.         return text
    
  1874. 
    
  1875. Calling this function with the value ``'de'`` will give you ``"Willkommen"``,
    
  1876. regardless of :setting:`LANGUAGE_CODE` and language set by middleware.
    
  1877. 
    
  1878. Functions of particular interest are
    
  1879. :func:`django.utils.translation.get_language()` which returns the language used
    
  1880. in the current thread, :func:`django.utils.translation.activate()` which
    
  1881. activates a translation catalog for the current thread, and
    
  1882. :func:`django.utils.translation.check_for_language()`
    
  1883. which checks if the given language is supported by Django.
    
  1884. 
    
  1885. To help write more concise code, there is also a context manager
    
  1886. :func:`django.utils.translation.override()` that stores the current language on
    
  1887. enter and restores it on exit. With it, the above example becomes::
    
  1888. 
    
  1889.     from django.utils import translation
    
  1890. 
    
  1891.     def welcome_translated(language):
    
  1892.         with translation.override(language):
    
  1893.             return translation.gettext('welcome')
    
  1894. 
    
  1895. Language cookie
    
  1896. ---------------
    
  1897. 
    
  1898. A number of settings can be used to adjust language cookie options:
    
  1899. 
    
  1900. * :setting:`LANGUAGE_COOKIE_NAME`
    
  1901. * :setting:`LANGUAGE_COOKIE_AGE`
    
  1902. * :setting:`LANGUAGE_COOKIE_DOMAIN`
    
  1903. * :setting:`LANGUAGE_COOKIE_HTTPONLY`
    
  1904. * :setting:`LANGUAGE_COOKIE_PATH`
    
  1905. * :setting:`LANGUAGE_COOKIE_SAMESITE`
    
  1906. * :setting:`LANGUAGE_COOKIE_SECURE`
    
  1907. 
    
  1908. Implementation notes
    
  1909. ====================
    
  1910. 
    
  1911. .. _specialties-of-django-i18n:
    
  1912. 
    
  1913. Specialties of Django translation
    
  1914. ---------------------------------
    
  1915. 
    
  1916. Django's translation machinery uses the standard ``gettext`` module that comes
    
  1917. with Python. If you know ``gettext``, you might note these specialties in the
    
  1918. way Django does translation:
    
  1919. 
    
  1920. * The string domain is ``django`` or ``djangojs``. This string domain is
    
  1921.   used to differentiate between different programs that store their data
    
  1922.   in a common message-file library (usually ``/usr/share/locale/``). The
    
  1923.   ``django`` domain is used for Python and template translation strings
    
  1924.   and is loaded into the global translation catalogs. The ``djangojs``
    
  1925.   domain is only used for JavaScript translation catalogs to make sure
    
  1926.   that those are as small as possible.
    
  1927. * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
    
  1928.   ``xgettext`` and ``msgfmt``. This is mostly for convenience.
    
  1929. 
    
  1930. .. _how-django-discovers-language-preference:
    
  1931. 
    
  1932. How Django discovers language preference
    
  1933. ----------------------------------------
    
  1934. 
    
  1935. Once you've prepared your translations -- or, if you want to use the
    
  1936. translations that come with Django -- you'll need to activate translation for
    
  1937. your app.
    
  1938. 
    
  1939. Behind the scenes, Django has a very flexible model of deciding which language
    
  1940. should be used -- installation-wide, for a particular user, or both.
    
  1941. 
    
  1942. To set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.
    
  1943. Django uses this language as the default translation -- the final attempt if no
    
  1944. better matching translation is found through one of the methods employed by the
    
  1945. locale middleware (see below).
    
  1946. 
    
  1947. If all you want is to run Django with your native language all you need to do
    
  1948. is set :setting:`LANGUAGE_CODE` and make sure the corresponding :term:`message
    
  1949. files <message file>` and their compiled versions (``.mo``) exist.
    
  1950. 
    
  1951. If you want to let each individual user specify which language they
    
  1952. prefer, then you also need to use the ``LocaleMiddleware``.
    
  1953. ``LocaleMiddleware`` enables language selection based on data from the request.
    
  1954. It customizes content for each user.
    
  1955. 
    
  1956. To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
    
  1957. to your :setting:`MIDDLEWARE` setting. Because middleware order matters, follow
    
  1958. these guidelines:
    
  1959. 
    
  1960. * Make sure it's one of the first middleware installed.
    
  1961. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
    
  1962.   makes use of session data. And it should come before ``CommonMiddleware``
    
  1963.   because ``CommonMiddleware`` needs an activated language in order
    
  1964.   to resolve the requested URL.
    
  1965. * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
    
  1966. 
    
  1967. For example, your :setting:`MIDDLEWARE` might look like this::
    
  1968. 
    
  1969.     MIDDLEWARE = [
    
  1970.        'django.contrib.sessions.middleware.SessionMiddleware',
    
  1971.        'django.middleware.locale.LocaleMiddleware',
    
  1972.        'django.middleware.common.CommonMiddleware',
    
  1973.     ]
    
  1974. 
    
  1975. (For more on middleware, see the :doc:`middleware documentation
    
  1976. </topics/http/middleware>`.)
    
  1977. 
    
  1978. ``LocaleMiddleware`` tries to determine the user's language preference by
    
  1979. following this algorithm:
    
  1980. 
    
  1981. * First, it looks for the language prefix in the requested URL.  This is
    
  1982.   only performed when you are using the ``i18n_patterns`` function in your
    
  1983.   root URLconf. See :ref:`url-internationalization` for more information
    
  1984.   about the language prefix and how to internationalize URL patterns.
    
  1985. 
    
  1986. * Failing that, it looks for a cookie.
    
  1987. 
    
  1988.   The name of the cookie used is set by the :setting:`LANGUAGE_COOKIE_NAME`
    
  1989.   setting. (The default name is ``django_language``.)
    
  1990. 
    
  1991. * Failing that, it looks at the ``Accept-Language`` HTTP header. This
    
  1992.   header is sent by your browser and tells the server which language(s) you
    
  1993.   prefer, in order by priority. Django tries each language in the header
    
  1994.   until it finds one with available translations.
    
  1995. 
    
  1996. * Failing that, it uses the global :setting:`LANGUAGE_CODE` setting.
    
  1997. 
    
  1998. .. _locale-middleware-notes:
    
  1999. 
    
  2000. Notes:
    
  2001. 
    
  2002. * In each of these places, the language preference is expected to be in the
    
  2003.   standard :term:`language format<language code>`, as a string. For example,
    
  2004.   Brazilian Portuguese is ``pt-br``.
    
  2005. 
    
  2006. * If a base language is available but the sublanguage specified is not,
    
  2007.   Django uses the base language. For example, if a user specifies ``de-at``
    
  2008.   (Austrian German) but Django only has ``de`` available, Django uses
    
  2009.   ``de``.
    
  2010. 
    
  2011. * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
    
  2012.   If you want to restrict the language selection to a subset of provided
    
  2013.   languages (because your application doesn't provide all those languages),
    
  2014.   set :setting:`LANGUAGES` to a list of languages. For example::
    
  2015. 
    
  2016.       LANGUAGES = [
    
  2017.           ('de', _('German')),
    
  2018.           ('en', _('English')),
    
  2019.       ]
    
  2020. 
    
  2021.   This example restricts languages that are available for automatic
    
  2022.   selection to German and English (and any sublanguage, like ``de-ch`` or
    
  2023.   ``en-us``).
    
  2024. 
    
  2025. * If you define a custom :setting:`LANGUAGES` setting, as explained in the
    
  2026.   previous bullet, you can mark the language names as translation strings
    
  2027.   -- but use :func:`~django.utils.translation.gettext_lazy` instead of
    
  2028.   :func:`~django.utils.translation.gettext` to avoid a circular import.
    
  2029. 
    
  2030.   Here's a sample settings file::
    
  2031. 
    
  2032.       from django.utils.translation import gettext_lazy as _
    
  2033. 
    
  2034.       LANGUAGES = [
    
  2035.           ('de', _('German')),
    
  2036.           ('en', _('English')),
    
  2037.       ]
    
  2038. 
    
  2039. Once ``LocaleMiddleware`` determines the user's preference, it makes this
    
  2040. preference available as ``request.LANGUAGE_CODE`` for each
    
  2041. :class:`~django.http.HttpRequest`. Feel free to read this value in your view
    
  2042. code. Here's an example::
    
  2043. 
    
  2044.     from django.http import HttpResponse
    
  2045. 
    
  2046.     def hello_world(request, count):
    
  2047.         if request.LANGUAGE_CODE == 'de-at':
    
  2048.             return HttpResponse("You prefer to read Austrian German.")
    
  2049.         else:
    
  2050.             return HttpResponse("You prefer to read another language.")
    
  2051. 
    
  2052. Note that, with static (middleware-less) translation, the language is in
    
  2053. ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
    
  2054. in ``request.LANGUAGE_CODE``.
    
  2055. 
    
  2056. .. _settings file: ../settings/
    
  2057. .. _middleware documentation: ../middleware/
    
  2058. .. _session: ../sessions/
    
  2059. .. _request object: ../request_response/#httprequest-objects
    
  2060. 
    
  2061. .. _how-django-discovers-translations:
    
  2062. 
    
  2063. How Django discovers translations
    
  2064. ---------------------------------
    
  2065. 
    
  2066. At runtime, Django builds an in-memory unified catalog of literals-translations.
    
  2067. To achieve this it looks for translations by following this algorithm regarding
    
  2068. the order in which it examines the different file paths to load the compiled
    
  2069. :term:`message files <message file>` (``.mo``) and the precedence of multiple
    
  2070. translations for the same literal:
    
  2071. 
    
  2072. #. The directories listed in :setting:`LOCALE_PATHS` have the highest
    
  2073.    precedence, with the ones appearing first having higher precedence than
    
  2074.    the ones appearing later.
    
  2075. #. Then, it looks for and uses if it exists a ``locale`` directory in each
    
  2076.    of the installed apps listed in :setting:`INSTALLED_APPS`.  The ones
    
  2077.    appearing first have higher precedence than the ones appearing later.
    
  2078. #. Finally, the Django-provided base translation in ``django/conf/locale``
    
  2079.    is used as a fallback.
    
  2080. 
    
  2081. .. seealso::
    
  2082. 
    
  2083.     The translations for literals included in JavaScript assets are looked up
    
  2084.     following a similar but not identical algorithm. See
    
  2085.     :class:`.JavaScriptCatalog` for more details.
    
  2086. 
    
  2087.     You can also put :ref:`custom format files <custom-format-files>` in the
    
  2088.     :setting:`LOCALE_PATHS` directories if you also set
    
  2089.     :setting:`FORMAT_MODULE_PATH`.
    
  2090. 
    
  2091. In all cases the name of the directory containing the translation is expected to
    
  2092. be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, ``es_AR``,
    
  2093. etc. Untranslated strings for territorial language variants use the translations
    
  2094. of the generic language. For example, untranslated ``pt_BR`` strings use ``pt``
    
  2095. translations.
    
  2096. 
    
  2097. This way, you can write applications that include their own translations, and
    
  2098. you can override base translations in your project. Or, you can build a big
    
  2099. project out of several apps and put all translations into one big common
    
  2100. message file specific to the project you are composing. The choice is yours.
    
  2101. 
    
  2102. All message file repositories are structured the same way. They are:
    
  2103. 
    
  2104. * All paths listed in :setting:`LOCALE_PATHS` in your settings file are
    
  2105.   searched for ``<language>/LC_MESSAGES/django.(po|mo)``
    
  2106. * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
    
  2107. * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
    
  2108. 
    
  2109. To create message files, you use the :djadmin:`django-admin makemessages <makemessages>`
    
  2110. tool. And you use :djadmin:`django-admin compilemessages <compilemessages>`
    
  2111. to produce the binary ``.mo`` files that are used by ``gettext``.
    
  2112. 
    
  2113. You can also run :djadmin:`django-admin compilemessages
    
  2114. --settings=path.to.settings <compilemessages>` to make the compiler process all
    
  2115. the directories in your :setting:`LOCALE_PATHS` setting.
    
  2116. 
    
  2117. Using a non-English base language
    
  2118. ---------------------------------
    
  2119. 
    
  2120. Django makes the general assumption that the original strings in a translatable
    
  2121. project are written in English. You can choose another language, but you must be
    
  2122. aware of certain limitations:
    
  2123. 
    
  2124. * ``gettext`` only provides two plural forms for the original messages, so you
    
  2125.   will also need to provide a translation for the base language to include all
    
  2126.   plural forms if the plural rules for the base language are different from
    
  2127.   English.
    
  2128. 
    
  2129. * When an English variant is activated and English strings are missing, the
    
  2130.   fallback language will not be the :setting:`LANGUAGE_CODE` of the project,
    
  2131.   but the original strings. For example, an English user visiting a site with
    
  2132.   :setting:`LANGUAGE_CODE` set to Spanish and original strings written in
    
  2133.   Russian will see Russian text rather than Spanish.