Debian Codegraph @

docs/topics/i18n/translation.txt

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