translation.txt 78 KB

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