translation.txt 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  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. .. versionchanged:: 4.2
  537. In older versions, ``asvar`` instances weren't marked as safe for (HTML)
  538. output purposes.
  539. ``{% blocktranslate %}`` also supports :ref:`contextual
  540. markers<contextual-markers>` using the ``context`` keyword:
  541. .. code-block:: html+django
  542. {% blocktranslate with name=user.username context "greeting" %}Hi {{ name }}{% endblocktranslate %}
  543. Another feature ``{% blocktranslate %}`` supports is the ``trimmed`` option.
  544. This option will remove newline characters from the beginning and the end of
  545. the content of the ``{% blocktranslate %}`` tag, replace any whitespace at the
  546. beginning and end of a line and merge all lines into one using a space
  547. character to separate them. This is quite useful for indenting the content of a
  548. ``{% blocktranslate %}`` tag without having the indentation characters end up
  549. in the corresponding entry in the ``.po`` file, which makes the translation
  550. process easier.
  551. For instance, the following ``{% blocktranslate %}`` tag:
  552. .. code-block:: html+django
  553. {% blocktranslate trimmed %}
  554. First sentence.
  555. Second paragraph.
  556. {% endblocktranslate %}
  557. will result in the entry ``"First sentence. Second paragraph."`` in the ``.po``
  558. file, compared to ``"\n First sentence.\n Second paragraph.\n"``, if the
  559. ``trimmed`` option had not been specified.
  560. String literals passed to tags and filters
  561. ------------------------------------------
  562. You can translate string literals passed as arguments to tags and filters
  563. by using the familiar ``_()`` syntax:
  564. .. code-block:: html+django
  565. {% some_tag _("Page not found") value|yesno:_("yes,no") %}
  566. In this case, both the tag and the filter will see the translated string,
  567. so they don't need to be aware of translations.
  568. .. note::
  569. In this example, the translation infrastructure will be passed the string
  570. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  571. translated string will need to contain the comma so that the filter
  572. parsing code knows how to split up the arguments. For example, a German
  573. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  574. (keeping the comma intact).
  575. .. _translator-comments-in-templates:
  576. Comments for translators in templates
  577. -------------------------------------
  578. Just like with :ref:`Python code <translator-comments>`, these notes for
  579. translators can be specified using comments, either with the :ttag:`comment`
  580. tag:
  581. .. code-block:: html+django
  582. {% comment %}Translators: View verb{% endcomment %}
  583. {% translate "View" %}
  584. {% comment %}Translators: Short intro blurb{% endcomment %}
  585. <p>{% blocktranslate %}A multiline translatable
  586. literal.{% endblocktranslate %}</p>
  587. or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:
  588. .. code-block:: html+django
  589. {# Translators: Label of a button that triggers search #}
  590. <button type="submit">{% translate "Go" %}</button>
  591. {# Translators: This is a text of the base template #}
  592. {% blocktranslate %}Ambiguous translatable block of text{% endblocktranslate %}
  593. .. note:: Just for completeness, these are the corresponding fragments of the
  594. resulting ``.po`` file:
  595. .. code-block:: po
  596. #. Translators: View verb
  597. # path/to/template/file.html:10
  598. msgid "View"
  599. msgstr ""
  600. #. Translators: Short intro blurb
  601. # path/to/template/file.html:13
  602. msgid ""
  603. "A multiline translatable"
  604. "literal."
  605. msgstr ""
  606. # ...
  607. #. Translators: Label of a button that triggers search
  608. # path/to/template/file.html:100
  609. msgid "Go"
  610. msgstr ""
  611. #. Translators: This is a text of the base template
  612. # path/to/template/file.html:103
  613. msgid "Ambiguous translatable block of text"
  614. msgstr ""
  615. .. templatetag:: language
  616. Switching language in templates
  617. -------------------------------
  618. If you want to select a language within a template, you can use the
  619. ``language`` template tag:
  620. .. code-block:: html+django
  621. {% load i18n %}
  622. {% get_current_language as LANGUAGE_CODE %}
  623. <!-- Current language: {{ LANGUAGE_CODE }} -->
  624. <p>{% translate "Welcome to our page" %}</p>
  625. {% language 'en' %}
  626. {% get_current_language as LANGUAGE_CODE %}
  627. <!-- Current language: {{ LANGUAGE_CODE }} -->
  628. <p>{% translate "Welcome to our page" %}</p>
  629. {% endlanguage %}
  630. While the first occurrence of "Welcome to our page" uses the current language,
  631. the second will always be in English.
  632. .. _i18n-template-tags:
  633. Other tags
  634. ----------
  635. These tags also require a ``{% load i18n %}``.
  636. .. templatetag:: get_available_languages
  637. ``get_available_languages``
  638. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  639. ``{% get_available_languages as LANGUAGES %}`` returns a list of tuples in
  640. which the first element is the :term:`language code` and the second is the
  641. language name (translated into the currently active locale).
  642. .. templatetag:: get_current_language
  643. ``get_current_language``
  644. ~~~~~~~~~~~~~~~~~~~~~~~~
  645. ``{% get_current_language as LANGUAGE_CODE %}`` returns the current user's
  646. preferred language as a string. Example: ``en-us``. See
  647. :ref:`how-django-discovers-language-preference`.
  648. .. templatetag:: get_current_language_bidi
  649. ``get_current_language_bidi``
  650. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  651. ``{% get_current_language_bidi as LANGUAGE_BIDI %}`` returns the current
  652. locale's direction. If ``True``, it's a right-to-left language, e.g. Hebrew,
  653. Arabic. If ``False`` it's a left-to-right language, e.g. English, French,
  654. German, etc.
  655. .. _template-translation-vars:
  656. ``i18n`` context processor
  657. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  658. If you enable the :class:`django.template.context_processors.i18n` context
  659. processor, then each ``RequestContext`` will have access to ``LANGUAGES``,
  660. ``LANGUAGE_CODE``, and ``LANGUAGE_BIDI`` as defined above.
  661. .. templatetag:: get_language_info
  662. ``get_language_info``
  663. ~~~~~~~~~~~~~~~~~~~~~
  664. You can also retrieve information about any of the available languages using
  665. provided template tags and filters. To get information about a single language,
  666. use the ``{% get_language_info %}`` tag:
  667. .. code-block:: html+django
  668. {% get_language_info for LANGUAGE_CODE as lang %}
  669. {% get_language_info for "pl" as lang %}
  670. You can then access the information:
  671. .. code-block:: html+django
  672. Language code: {{ lang.code }}<br>
  673. Name of language: {{ lang.name_local }}<br>
  674. Name in English: {{ lang.name }}<br>
  675. Bi-directional: {{ lang.bidi }}
  676. Name in the active language: {{ lang.name_translated }}
  677. .. templatetag:: get_language_info_list
  678. ``get_language_info_list``
  679. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  680. You can also use the ``{% get_language_info_list %}`` template tag to retrieve
  681. information for a list of languages (e.g. active languages as specified in
  682. :setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
  683. view <set_language-redirect-view>` for an example of how to display a language
  684. selector using ``{% get_language_info_list %}``.
  685. In addition to :setting:`LANGUAGES` style list of tuples,
  686. ``{% get_language_info_list %}`` supports lists of language codes.
  687. If you do this in your view:
  688. .. code-block:: python
  689. context = {"available_languages": ["en", "es", "fr"]}
  690. return render(request, "mytemplate.html", context)
  691. you can iterate over those languages in the template:
  692. .. code-block:: html+django
  693. {% get_language_info_list for available_languages as langs %}
  694. {% for lang in langs %} ... {% endfor %}
  695. .. templatefilter:: language_name
  696. .. templatefilter:: language_name_local
  697. .. templatefilter:: language_bidi
  698. .. templatefilter:: language_name_translated
  699. Template filters
  700. ~~~~~~~~~~~~~~~~
  701. There are also some filters available for convenience:
  702. * ``{{ LANGUAGE_CODE|language_name }}`` ("German")
  703. * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
  704. * ``{{ LANGUAGE_CODE|language_bidi }}`` (False)
  705. * ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active language is Czech)
  706. Internationalization: in JavaScript code
  707. ========================================
  708. Adding translations to JavaScript poses some problems:
  709. * JavaScript code doesn't have access to a ``gettext`` implementation.
  710. * JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to
  711. be delivered by the server.
  712. * The translation catalogs for JavaScript should be kept as small as
  713. possible.
  714. Django provides an integrated solution for these problems: It passes the
  715. translations into JavaScript, so you can call ``gettext``, etc., from within
  716. JavaScript.
  717. The main solution to these problems is the following ``JavaScriptCatalog`` view,
  718. which generates a JavaScript code library with functions that mimic the
  719. ``gettext`` interface, plus an array of translation strings.
  720. The ``JavaScriptCatalog`` view
  721. ------------------------------
  722. .. module:: django.views.i18n
  723. .. class:: JavaScriptCatalog
  724. A view that produces a JavaScript code library with functions that mimic
  725. the ``gettext`` interface, plus an array of translation strings.
  726. **Attributes**
  727. .. attribute:: domain
  728. Translation domain containing strings to add in the view output.
  729. Defaults to ``'djangojs'``.
  730. .. attribute:: packages
  731. A list of :attr:`application names <django.apps.AppConfig.name>` among
  732. installed applications. Those apps should contain a ``locale``
  733. directory. All those catalogs plus all catalogs found in
  734. :setting:`LOCALE_PATHS` (which are always included) are merged into one
  735. catalog. Defaults to ``None``, which means that all available
  736. translations from all :setting:`INSTALLED_APPS` are provided in the
  737. JavaScript output.
  738. **Example with default values**::
  739. from django.views.i18n import JavaScriptCatalog
  740. urlpatterns = [
  741. path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
  742. ]
  743. **Example with custom packages**::
  744. urlpatterns = [
  745. path(
  746. "jsi18n/myapp/",
  747. JavaScriptCatalog.as_view(packages=["your.app.label"]),
  748. name="javascript-catalog",
  749. ),
  750. ]
  751. If your root URLconf uses :func:`~django.conf.urls.i18n.i18n_patterns`,
  752. ``JavaScriptCatalog`` must also be wrapped by ``i18n_patterns()`` for the
  753. catalog to be correctly generated.
  754. **Example with** ``i18n_patterns()``::
  755. from django.conf.urls.i18n import i18n_patterns
  756. urlpatterns = i18n_patterns(
  757. path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
  758. )
  759. The precedence of translations is such that the packages appearing later in the
  760. ``packages`` argument have higher precedence than the ones appearing at the
  761. beginning. This is important in the case of clashing translations for the same
  762. literal.
  763. If you use more than one ``JavaScriptCatalog`` view on a site and some of them
  764. define the same strings, the strings in the catalog that was loaded last take
  765. precedence.
  766. Using the JavaScript translation catalog
  767. ----------------------------------------
  768. To use the catalog, pull in the dynamically generated script like this:
  769. .. code-block:: html+django
  770. <script src="{% url 'javascript-catalog' %}"></script>
  771. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
  772. When the catalog is loaded, your JavaScript code can use the following methods:
  773. * ``gettext``
  774. * ``ngettext``
  775. * ``interpolate``
  776. * ``get_format``
  777. * ``gettext_noop``
  778. * ``pgettext``
  779. * ``npgettext``
  780. * ``pluralidx``
  781. ``gettext``
  782. ~~~~~~~~~~~
  783. The ``gettext`` function behaves similarly to the standard ``gettext``
  784. interface within your Python code::
  785. document.write(gettext("this is to be translated"))
  786. ``ngettext``
  787. ~~~~~~~~~~~~
  788. The ``ngettext`` function provides an interface to pluralize words and
  789. phrases:
  790. .. code-block:: javascript
  791. const objectCount = 1 // or 0, or 2, or 3, ...
  792. const string = ngettext(
  793. 'literal for the singular case',
  794. 'literal for the plural case',
  795. objectCount
  796. );
  797. ``interpolate``
  798. ~~~~~~~~~~~~~~~
  799. The ``interpolate`` function supports dynamically populating a format string.
  800. The interpolation syntax is borrowed from Python, so the ``interpolate``
  801. function supports both positional and named interpolation:
  802. * Positional interpolation: ``obj`` contains a JavaScript Array object
  803. whose elements values are then sequentially interpolated in their
  804. corresponding ``fmt`` placeholders in the same order they appear.
  805. For example:
  806. .. code-block:: javascript
  807. const formats = ngettext(
  808. 'There is %s object. Remaining: %s',
  809. 'There are %s objects. Remaining: %s',
  810. 11
  811. );
  812. const string = interpolate(formats, [11, 20]);
  813. // string is 'There are 11 objects. Remaining: 20'
  814. * Named interpolation: This mode is selected by passing the optional
  815. boolean ``named`` parameter as ``true``. ``obj`` contains a JavaScript
  816. object or associative array. For example:
  817. .. code-block:: javascript
  818. const data = {
  819. count: 10,
  820. total: 50
  821. };
  822. const formats = ngettext(
  823. 'Total: %(total)s, there is %(count)s object',
  824. 'there are %(count)s of a total of %(total)s objects',
  825. data.count
  826. );
  827. const string = interpolate(formats, data, true);
  828. You shouldn't go over the top with string interpolation, though: this is still
  829. JavaScript, so the code has to make repeated regular-expression substitutions.
  830. This isn't as fast as string interpolation in Python, so keep it to those
  831. cases where you really need it (for example, in conjunction with ``ngettext``
  832. to produce proper pluralizations).
  833. ``get_format``
  834. ~~~~~~~~~~~~~~
  835. The ``get_format`` function has access to the configured i18n formatting
  836. settings and can retrieve the format string for a given setting name:
  837. .. code-block:: javascript
  838. document.write(get_format('DATE_FORMAT'));
  839. // 'N j, Y'
  840. It has access to the following settings:
  841. * :setting:`DATE_FORMAT`
  842. * :setting:`DATE_INPUT_FORMATS`
  843. * :setting:`DATETIME_FORMAT`
  844. * :setting:`DATETIME_INPUT_FORMATS`
  845. * :setting:`DECIMAL_SEPARATOR`
  846. * :setting:`FIRST_DAY_OF_WEEK`
  847. * :setting:`MONTH_DAY_FORMAT`
  848. * :setting:`NUMBER_GROUPING`
  849. * :setting:`SHORT_DATE_FORMAT`
  850. * :setting:`SHORT_DATETIME_FORMAT`
  851. * :setting:`THOUSAND_SEPARATOR`
  852. * :setting:`TIME_FORMAT`
  853. * :setting:`TIME_INPUT_FORMATS`
  854. * :setting:`YEAR_MONTH_FORMAT`
  855. This is useful for maintaining formatting consistency with the Python-rendered
  856. values.
  857. ``gettext_noop``
  858. ~~~~~~~~~~~~~~~~
  859. This emulates the ``gettext`` function but does nothing, returning whatever
  860. is passed to it::
  861. document.write(gettext_noop("this will not be translated"))
  862. This is useful for stubbing out portions of the code that will need translation
  863. in the future.
  864. ``pgettext``
  865. ~~~~~~~~~~~~
  866. The ``pgettext`` function behaves like the Python variant
  867. (:func:`~django.utils.translation.pgettext()`), providing a contextually
  868. translated word::
  869. document.write(pgettext("month name", "May"))
  870. ``npgettext``
  871. ~~~~~~~~~~~~~
  872. The ``npgettext`` function also behaves like the Python variant
  873. (:func:`~django.utils.translation.npgettext()`), providing a **pluralized**
  874. contextually translated word:
  875. .. code-block:: javascript
  876. document.write(npgettext('group', 'party', 1));
  877. // party
  878. document.write(npgettext('group', 'party', 2));
  879. // parties
  880. ``pluralidx``
  881. ~~~~~~~~~~~~~
  882. The ``pluralidx`` function works in a similar way to the :tfilter:`pluralize`
  883. template filter, determining if a given ``count`` should use a plural form of
  884. a word or not:
  885. .. code-block:: javascript
  886. document.write(pluralidx(0));
  887. // true
  888. document.write(pluralidx(1));
  889. // false
  890. document.write(pluralidx(2));
  891. // true
  892. In the simplest case, if no custom pluralization is needed, this returns
  893. ``false`` for the integer ``1`` and ``true`` for all other numbers.
  894. However, pluralization is not this simple in all languages. If the language does
  895. not support pluralization, an empty value is provided.
  896. Additionally, if there are complex rules around pluralization, the catalog view
  897. will render a conditional expression. This will evaluate to either a ``true``
  898. (should pluralize) or ``false`` (should **not** pluralize) value.
  899. The ``JSONCatalog`` view
  900. ------------------------
  901. .. class:: JSONCatalog
  902. In order to use another client-side library to handle translations, you may
  903. want to take advantage of the ``JSONCatalog`` view. It's similar to
  904. :class:`~django.views.i18n.JavaScriptCatalog` but returns a JSON response.
  905. See the documentation for :class:`~django.views.i18n.JavaScriptCatalog`
  906. to learn about possible values and use of the ``domain`` and ``packages``
  907. attributes.
  908. The response format is as follows:
  909. .. code-block:: text
  910. {
  911. "catalog": {
  912. # Translations catalog
  913. },
  914. "formats": {
  915. # Language formats for date, time, etc.
  916. },
  917. "plural": "..." # Expression for plural forms, or null.
  918. }
  919. .. JSON doesn't allow comments so highlighting as JSON won't work here.
  920. Note on performance
  921. -------------------
  922. The various JavaScript/JSON i18n views generate the catalog from ``.mo`` files
  923. on every request. Since its output is constant, at least for a given version
  924. of a site, it's a good candidate for caching.
  925. Server-side caching will reduce CPU load. It's easily implemented with the
  926. :func:`~django.views.decorators.cache.cache_page` decorator. To trigger cache
  927. invalidation when your translations change, provide a version-dependent key
  928. prefix, as shown in the example below, or map the view at a version-dependent
  929. URL::
  930. from django.views.decorators.cache import cache_page
  931. from django.views.i18n import JavaScriptCatalog
  932. # The value returned by get_version() must change when translations change.
  933. urlpatterns = [
  934. path(
  935. "jsi18n/",
  936. cache_page(86400, key_prefix="jsi18n-%s" % get_version())(
  937. JavaScriptCatalog.as_view()
  938. ),
  939. name="javascript-catalog",
  940. ),
  941. ]
  942. Client-side caching will save bandwidth and make your site load faster. If
  943. you're using ETags (:class:`~django.middleware.http.ConditionalGetMiddleware`),
  944. you're already covered. Otherwise, you can apply :ref:`conditional decorators
  945. <conditional-decorators>`. In the following example, the cache is invalidated
  946. whenever you restart your application server::
  947. from django.utils import timezone
  948. from django.views.decorators.http import last_modified
  949. from django.views.i18n import JavaScriptCatalog
  950. last_modified_date = timezone.now()
  951. urlpatterns = [
  952. path(
  953. "jsi18n/",
  954. last_modified(lambda req, **kw: last_modified_date)(
  955. JavaScriptCatalog.as_view()
  956. ),
  957. name="javascript-catalog",
  958. ),
  959. ]
  960. You can even pre-generate the JavaScript catalog as part of your deployment
  961. procedure and serve it as a static file. This radical technique is implemented
  962. in django-statici18n_.
  963. .. _django-statici18n: https://django-statici18n.readthedocs.io/
  964. .. _url-internationalization:
  965. Internationalization: in URL patterns
  966. =====================================
  967. .. module:: django.conf.urls.i18n
  968. Django provides two mechanisms to internationalize URL patterns:
  969. * Adding the language prefix to the root of the URL patterns to make it
  970. possible for :class:`~django.middleware.locale.LocaleMiddleware` to detect
  971. the language to activate from the requested URL.
  972. * Making URL patterns themselves translatable via the
  973. :func:`django.utils.translation.gettext_lazy()` function.
  974. .. warning::
  975. Using either one of these features requires that an active language be set
  976. for each request; in other words, you need to have
  977. :class:`django.middleware.locale.LocaleMiddleware` in your
  978. :setting:`MIDDLEWARE` setting.
  979. Language prefix in URL patterns
  980. -------------------------------
  981. .. function:: i18n_patterns(*urls, prefix_default_language=True)
  982. This function can be used in a root URLconf and Django will automatically
  983. prepend the current active language code to all URL patterns defined within
  984. :func:`~django.conf.urls.i18n.i18n_patterns`.
  985. Setting ``prefix_default_language`` to ``False`` removes the prefix from the
  986. default language (:setting:`LANGUAGE_CODE`). This can be useful when adding
  987. translations to existing site so that the current URLs won't change.
  988. Example URL patterns::
  989. from django.conf.urls.i18n import i18n_patterns
  990. from django.urls import include, path
  991. from about import views as about_views
  992. from news import views as news_views
  993. from sitemap.views import sitemap
  994. urlpatterns = [
  995. path("sitemap.xml", sitemap, name="sitemap-xml"),
  996. ]
  997. news_patterns = (
  998. [
  999. path("", news_views.index, name="index"),
  1000. path("category/<slug:slug>/", news_views.category, name="category"),
  1001. path("<slug:slug>/", news_views.details, name="detail"),
  1002. ],
  1003. "news",
  1004. )
  1005. urlpatterns += i18n_patterns(
  1006. path("about/", about_views.main, name="about"),
  1007. path("news/", include(news_patterns, namespace="news")),
  1008. )
  1009. After defining these URL patterns, Django will automatically add the
  1010. language prefix to the URL patterns that were added by the ``i18n_patterns``
  1011. function. Example:
  1012. .. code-block:: pycon
  1013. >>> from django.urls import reverse
  1014. >>> from django.utils.translation import activate
  1015. >>> activate("en")
  1016. >>> reverse("sitemap-xml")
  1017. '/sitemap.xml'
  1018. >>> reverse("news:index")
  1019. '/en/news/'
  1020. >>> activate("nl")
  1021. >>> reverse("news:detail", kwargs={"slug": "news-slug"})
  1022. '/nl/news/news-slug/'
  1023. With ``prefix_default_language=False`` and ``LANGUAGE_CODE='en'``, the URLs
  1024. will be:
  1025. .. code-block:: pycon
  1026. >>> activate("en")
  1027. >>> reverse("news:index")
  1028. '/news/'
  1029. >>> activate("nl")
  1030. >>> reverse("news:index")
  1031. '/nl/news/'
  1032. .. warning::
  1033. :func:`~django.conf.urls.i18n.i18n_patterns` is only allowed in a root
  1034. URLconf. Using it within an included URLconf will throw an
  1035. :exc:`~django.core.exceptions.ImproperlyConfigured` exception.
  1036. .. warning::
  1037. Ensure that you don't have non-prefixed URL patterns that might collide
  1038. with an automatically-added language prefix.
  1039. .. _translating-urlpatterns:
  1040. Translating URL patterns
  1041. ------------------------
  1042. URL patterns can also be marked translatable using the
  1043. :func:`~django.utils.translation.gettext_lazy` function. Example::
  1044. from django.conf.urls.i18n import i18n_patterns
  1045. from django.urls import include, path
  1046. from django.utils.translation import gettext_lazy as _
  1047. from about import views as about_views
  1048. from news import views as news_views
  1049. from sitemaps.views import sitemap
  1050. urlpatterns = [
  1051. path("sitemap.xml", sitemap, name="sitemap-xml"),
  1052. ]
  1053. news_patterns = (
  1054. [
  1055. path("", news_views.index, name="index"),
  1056. path(_("category/<slug:slug>/"), news_views.category, name="category"),
  1057. path("<slug:slug>/", news_views.details, name="detail"),
  1058. ],
  1059. "news",
  1060. )
  1061. urlpatterns += i18n_patterns(
  1062. path(_("about/"), about_views.main, name="about"),
  1063. path(_("news/"), include(news_patterns, namespace="news")),
  1064. )
  1065. After you've created the translations, the :func:`~django.urls.reverse`
  1066. function will return the URL in the active language. Example:
  1067. .. code-block:: pycon
  1068. >>> from django.urls import reverse
  1069. >>> from django.utils.translation import activate
  1070. >>> activate("en")
  1071. >>> reverse("news:category", kwargs={"slug": "recent"})
  1072. '/en/news/category/recent/'
  1073. >>> activate("nl")
  1074. >>> reverse("news:category", kwargs={"slug": "recent"})
  1075. '/nl/nieuws/categorie/recent/'
  1076. .. warning::
  1077. In most cases, it's best to use translated URLs only within a language code
  1078. prefixed block of patterns (using
  1079. :func:`~django.conf.urls.i18n.i18n_patterns`), to avoid the possibility
  1080. that a carelessly translated URL causes a collision with a non-translated
  1081. URL pattern.
  1082. .. _reversing_in_templates:
  1083. Reversing in templates
  1084. ----------------------
  1085. If localized URLs get reversed in templates they always use the current
  1086. language. To link to a URL in another language use the :ttag:`language`
  1087. template tag. It enables the given language in the enclosed template section:
  1088. .. code-block:: html+django
  1089. {% load i18n %}
  1090. {% get_available_languages as languages %}
  1091. {% translate "View this category in:" %}
  1092. {% for lang_code, lang_name in languages %}
  1093. {% language lang_code %}
  1094. <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
  1095. {% endlanguage %}
  1096. {% endfor %}
  1097. The :ttag:`language` tag expects the language code as the only argument.
  1098. .. _how-to-create-language-files:
  1099. Localization: how to create language files
  1100. ==========================================
  1101. Once the string literals of an application have been tagged for later
  1102. translation, the translation themselves need to be written (or obtained). Here's
  1103. how that works.
  1104. Message files
  1105. -------------
  1106. The first step is to create a :term:`message file` for a new language. A message
  1107. file is a plain-text file, representing a single language, that contains all
  1108. available translation strings and how they should be represented in the given
  1109. language. Message files have a ``.po`` file extension.
  1110. Django comes with a tool, :djadmin:`django-admin makemessages
  1111. <makemessages>`, that automates the creation and upkeep of these files.
  1112. .. admonition:: Gettext utilities
  1113. The ``makemessages`` command (and ``compilemessages`` discussed later) use
  1114. commands from the GNU gettext toolset: ``xgettext``, ``msgfmt``,
  1115. ``msgmerge`` and ``msguniq``.
  1116. The minimum version of the ``gettext`` utilities supported is 0.15.
  1117. To create or update a message file, run this command:
  1118. .. code-block:: shell
  1119. django-admin makemessages -l de
  1120. ...where ``de`` is the :term:`locale name` for the message file you want to
  1121. create. For example, ``pt_BR`` for Brazilian Portuguese, ``de_AT`` for Austrian
  1122. German or ``id`` for Indonesian.
  1123. The script should be run from one of two places:
  1124. * The root directory of your Django project (the one that contains
  1125. ``manage.py``).
  1126. * The root directory of one of your Django apps.
  1127. The script runs over your project source tree or your application source tree
  1128. and pulls out all strings marked for translation (see
  1129. :ref:`how-django-discovers-translations` and be sure :setting:`LOCALE_PATHS`
  1130. is configured correctly). It creates (or updates) a message file in the
  1131. directory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the file will be
  1132. ``locale/de/LC_MESSAGES/django.po``.
  1133. When you run ``makemessages`` from the root directory of your project, the
  1134. extracted strings will be automatically distributed to the proper message files.
  1135. That is, a string extracted from a file of an app containing a ``locale``
  1136. directory will go in a message file under that directory. A string extracted
  1137. from a file of an app without any ``locale`` directory will either go in a
  1138. message file under the directory listed first in :setting:`LOCALE_PATHS` or
  1139. will generate an error if :setting:`LOCALE_PATHS` is empty.
  1140. By default :djadmin:`django-admin makemessages <makemessages>` examines every
  1141. file that has the ``.html``, ``.txt`` or ``.py`` file extension. If you want to
  1142. override that default, use the :option:`--extension <makemessages --extension>`
  1143. or ``-e`` option to specify the file extensions to examine:
  1144. .. code-block:: shell
  1145. django-admin makemessages -l de -e txt
  1146. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
  1147. multiple times:
  1148. .. code-block:: shell
  1149. django-admin makemessages -l de -e html,txt -e xml
  1150. .. warning::
  1151. When :ref:`creating message files from JavaScript source code
  1152. <creating-message-files-from-js-code>` you need to use the special
  1153. ``djangojs`` domain, **not** ``-e js``.
  1154. .. admonition:: Using Jinja2 templates?
  1155. :djadmin:`makemessages` doesn't understand the syntax of Jinja2 templates.
  1156. To extract strings from a project containing Jinja2 templates, use `Message
  1157. Extracting`_ from Babel_ instead.
  1158. Here's an example ``babel.cfg`` configuration file:
  1159. .. code-block:: ini
  1160. # Extraction from Python source files
  1161. [python: **.py]
  1162. # Extraction from Jinja2 templates
  1163. [jinja2: **.jinja]
  1164. extensions = jinja2.ext.with_
  1165. Make sure you list all extensions you're using! Otherwise Babel won't
  1166. recognize the tags defined by these extensions and will ignore Jinja2
  1167. templates containing them entirely.
  1168. Babel provides similar features to :djadmin:`makemessages`, can replace it
  1169. in general, and doesn't depend on ``gettext``. For more information, read
  1170. its documentation about `working with message catalogs`_.
  1171. .. _Message extracting: https://babel.pocoo.org/en/latest/messages.html#message-extraction
  1172. .. _Babel: https://babel.pocoo.org/en/latest/
  1173. .. _working with message catalogs: https://babel.pocoo.org/en/latest/messages.html
  1174. .. admonition:: No gettext?
  1175. If you don't have the ``gettext`` utilities installed,
  1176. :djadmin:`makemessages` will create empty files. If that's the case, either
  1177. install the ``gettext`` utilities or copy the English message file
  1178. (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
  1179. point, which is an empty translation file.
  1180. .. admonition:: Working on Windows?
  1181. If you're using Windows and need to install the GNU gettext utilities so
  1182. :djadmin:`makemessages` works, see :ref:`gettext_on_windows` for more
  1183. information.
  1184. Each ``.po`` file contains a small bit of metadata, such as the translation
  1185. maintainer's contact information, but the bulk of the file is a list of
  1186. **messages** -- mappings between translation strings and the actual translated
  1187. text for the particular language.
  1188. For example, if your Django app contained a translation string for the text
  1189. ``"Welcome to my site."``, like so::
  1190. _("Welcome to my site.")
  1191. ...then :djadmin:`django-admin makemessages <makemessages>` will have created
  1192. a ``.po`` file containing the following snippet -- a message:
  1193. .. code-block:: po
  1194. #: path/to/python/module.py:23
  1195. msgid "Welcome to my site."
  1196. msgstr ""
  1197. A quick explanation:
  1198. * ``msgid`` is the translation string, which appears in the source. Don't
  1199. change it.
  1200. * ``msgstr`` is where you put the language-specific translation. It starts
  1201. out empty, so it's your responsibility to change it. Make sure you keep
  1202. the quotes around your translation.
  1203. * As a convenience, each message includes, in the form of a comment line
  1204. prefixed with ``#`` and located above the ``msgid`` line, the filename and
  1205. line number from which the translation string was gleaned.
  1206. Long messages are a special case. There, the first string directly after the
  1207. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
  1208. written over the next few lines as one string per line. Those strings are
  1209. directly concatenated. Don't forget trailing spaces within the strings;
  1210. otherwise, they'll be tacked together without whitespace!
  1211. .. admonition:: Mind your charset
  1212. Due to the way the ``gettext`` tools work internally and because we want to
  1213. allow non-ASCII source strings in Django's core and your applications, you
  1214. **must** use UTF-8 as the encoding for your ``.po`` files (the default when
  1215. ``.po`` files are created). This means that everybody will be using the
  1216. same encoding, which is important when Django processes the ``.po`` files.
  1217. .. admonition:: Fuzzy entries
  1218. :djadmin:`makemessages` sometimes generates translation entries marked as
  1219. fuzzy, e.g. when translations are inferred from previously translated
  1220. strings. By default, fuzzy entries are **not** processed by
  1221. :djadmin:`compilemessages`.
  1222. To reexamine all source code and templates for new translation strings and
  1223. update all message files for **all** languages, run this:
  1224. .. code-block:: shell
  1225. django-admin makemessages -a
  1226. Compiling message files
  1227. -----------------------
  1228. After you create your message file -- and each time you make changes to it --
  1229. you'll need to compile it into a more efficient form, for use by ``gettext``. Do
  1230. this with the :djadmin:`django-admin compilemessages <compilemessages>`
  1231. utility.
  1232. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
  1233. are binary files optimized for use by ``gettext``. In the same directory from
  1234. which you ran :djadmin:`django-admin makemessages <makemessages>`, run
  1235. :djadmin:`django-admin compilemessages <compilemessages>` like this:
  1236. .. code-block:: shell
  1237. django-admin compilemessages
  1238. That's it. Your translations are ready for use.
  1239. .. admonition:: Working on Windows?
  1240. If you're using Windows and need to install the GNU gettext utilities so
  1241. :djadmin:`django-admin compilemessages <compilemessages>` works see
  1242. :ref:`gettext_on_windows` for more information.
  1243. .. admonition:: ``.po`` files: Encoding and BOM usage.
  1244. Django only supports ``.po`` files encoded in UTF-8 and without any BOM
  1245. (Byte Order Mark) so if your text editor adds such marks to the beginning of
  1246. files by default then you will need to reconfigure it.
  1247. Troubleshooting: ``gettext()`` incorrectly detects ``python-format`` in strings with percent signs
  1248. --------------------------------------------------------------------------------------------------
  1249. In some cases, such as strings with a percent sign followed by a space and a
  1250. :ref:`string conversion type <old-string-formatting>` (e.g.
  1251. ``_("10% interest")``), :func:`~django.utils.translation.gettext` incorrectly
  1252. flags strings with ``python-format``.
  1253. If you try to compile message files with incorrectly flagged strings, you'll
  1254. get an error message like ``number of format specifications in 'msgid' and
  1255. 'msgstr' does not match`` or ``'msgstr' is not a valid Python format string,
  1256. unlike 'msgid'``.
  1257. To workaround this, you can escape percent signs by adding a second percent
  1258. sign::
  1259. from django.utils.translation import gettext as _
  1260. output = _("10%% interest")
  1261. Or you can use ``no-python-format`` so that all percent signs are treated as
  1262. literals::
  1263. # xgettext:no-python-format
  1264. output = _("10% interest")
  1265. .. _creating-message-files-from-js-code:
  1266. Creating message files from JavaScript source code
  1267. --------------------------------------------------
  1268. You create and update the message files the same way as the other Django message
  1269. files -- with the :djadmin:`django-admin makemessages <makemessages>` tool.
  1270. The only difference is you need to explicitly specify what in gettext parlance
  1271. is known as a domain in this case the ``djangojs`` domain, by providing a ``-d
  1272. djangojs`` parameter, like this:
  1273. .. code-block:: shell
  1274. django-admin makemessages -d djangojs -l de
  1275. This would create or update the message file for JavaScript for German. After
  1276. updating message files, run :djadmin:`django-admin compilemessages
  1277. <compilemessages>` the same way as you do with normal Django message files.
  1278. .. _gettext_on_windows:
  1279. ``gettext`` on Windows
  1280. ----------------------
  1281. This is only needed for people who either want to extract message IDs or compile
  1282. message files (``.po``). Translation work itself involves editing existing
  1283. files of this type, but if you want to create your own message files, or want
  1284. to test or compile a changed message file, download `a precompiled binary
  1285. installer <https://mlocati.github.io/articles/gettext-iconv-windows.html>`_.
  1286. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
  1287. the ``xgettext --version`` command works properly. Do not attempt to use Django
  1288. translation utilities with a ``gettext`` package if the command ``xgettext
  1289. --version`` entered at a Windows command prompt causes a popup window saying
  1290. "``xgettext.exe`` has generated errors and will be closed by Windows".
  1291. .. _customizing-makemessages:
  1292. Customizing the ``makemessages`` command
  1293. ----------------------------------------
  1294. If you want to pass additional parameters to ``xgettext``, you need to create a
  1295. custom :djadmin:`makemessages` command and override its ``xgettext_options``
  1296. attribute::
  1297. from django.core.management.commands import makemessages
  1298. class Command(makemessages.Command):
  1299. xgettext_options = makemessages.Command.xgettext_options + ["--keyword=mytrans"]
  1300. If you need more flexibility, you could also add a new argument to your custom
  1301. :djadmin:`makemessages` command::
  1302. from django.core.management.commands import makemessages
  1303. class Command(makemessages.Command):
  1304. def add_arguments(self, parser):
  1305. super().add_arguments(parser)
  1306. parser.add_argument(
  1307. "--extra-keyword",
  1308. dest="xgettext_keywords",
  1309. action="append",
  1310. )
  1311. def handle(self, *args, **options):
  1312. xgettext_keywords = options.pop("xgettext_keywords")
  1313. if xgettext_keywords:
  1314. self.xgettext_options = makemessages.Command.xgettext_options[:] + [
  1315. "--keyword=%s" % kwd for kwd in xgettext_keywords
  1316. ]
  1317. super().handle(*args, **options)
  1318. Miscellaneous
  1319. =============
  1320. .. _set_language-redirect-view:
  1321. The ``set_language`` redirect view
  1322. ----------------------------------
  1323. .. currentmodule:: django.views.i18n
  1324. .. function:: set_language(request)
  1325. As a convenience, Django comes with a view, :func:`django.views.i18n.set_language`,
  1326. that sets a user's language preference and redirects to a given URL or, by default,
  1327. back to the previous page.
  1328. Activate this view by adding the following line to your URLconf::
  1329. path("i18n/", include("django.conf.urls.i18n")),
  1330. (Note that this example makes the view available at ``/i18n/setlang/``.)
  1331. .. warning::
  1332. Make sure that you don't include the above URL within
  1333. :func:`~django.conf.urls.i18n.i18n_patterns` - it needs to be
  1334. language-independent itself to work correctly.
  1335. The view expects to be called via the ``POST`` method, with a ``language``
  1336. parameter set in request. If session support is enabled, the view saves the
  1337. language choice in the user's session. It also saves the language choice in a
  1338. cookie that is named ``django_language`` by default. (The name can be changed
  1339. through the :setting:`LANGUAGE_COOKIE_NAME` setting.)
  1340. After setting the language choice, Django looks for a ``next`` parameter in the
  1341. ``POST`` or ``GET`` data. If that is found and Django considers it to be a safe
  1342. URL (i.e. it doesn't point to a different host and uses a safe scheme), a
  1343. redirect to that URL will be performed. Otherwise, Django may fall back to
  1344. redirecting the user to the URL from the ``Referer`` header or, if it is not
  1345. set, to ``/``, depending on the nature of the request:
  1346. * If the request accepts HTML content (based on its ``Accept`` HTTP header),
  1347. the fallback will always be performed.
  1348. * If the request doesn't accept HTML, the fallback will be performed only if
  1349. the ``next`` parameter was set. Otherwise a 204 status code (No Content) will
  1350. be returned.
  1351. Here's example HTML template code:
  1352. .. code-block:: html+django
  1353. {% load i18n %}
  1354. <form action="{% url 'set_language' %}" method="post">{% csrf_token %}
  1355. <input name="next" type="hidden" value="{{ redirect_to }}">
  1356. <select name="language">
  1357. {% get_current_language as LANGUAGE_CODE %}
  1358. {% get_available_languages as LANGUAGES %}
  1359. {% get_language_info_list for LANGUAGES as languages %}
  1360. {% for language in languages %}
  1361. <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
  1362. {{ language.name_local }} ({{ language.code }})
  1363. </option>
  1364. {% endfor %}
  1365. </select>
  1366. <input type="submit" value="Go">
  1367. </form>
  1368. In this example, Django looks up the URL of the page to which the user will be
  1369. redirected in the ``redirect_to`` context variable.
  1370. .. _explicitly-setting-the-active-language:
  1371. Explicitly setting the active language
  1372. --------------------------------------
  1373. You may want to set the active language for the current session explicitly. Perhaps
  1374. a user's language preference is retrieved from another system, for example.
  1375. You've already been introduced to :func:`django.utils.translation.activate()`. That
  1376. applies to the current thread only. To persist the language for the entire
  1377. session in a cookie, set the :setting:`LANGUAGE_COOKIE_NAME` cookie on the
  1378. response::
  1379. from django.conf import settings
  1380. from django.http import HttpResponse
  1381. from django.utils import translation
  1382. user_language = "fr"
  1383. translation.activate(user_language)
  1384. response = HttpResponse(...)
  1385. response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
  1386. You would typically want to use both: :func:`django.utils.translation.activate()`
  1387. changes the language for this thread, and setting the cookie makes this
  1388. preference persist in future requests.
  1389. Using translations outside views and templates
  1390. ----------------------------------------------
  1391. While Django provides a rich set of i18n tools for use in views and templates,
  1392. it does not restrict the usage to Django-specific code. The Django translation
  1393. mechanisms can be used to translate arbitrary texts to any language that is
  1394. supported by Django (as long as an appropriate translation catalog exists, of
  1395. course). You can load a translation catalog, activate it and translate text to
  1396. language of your choice, but remember to switch back to original language, as
  1397. activating a translation catalog is done on per-thread basis and such change
  1398. will affect code running in the same thread.
  1399. For example::
  1400. from django.utils import translation
  1401. def welcome_translated(language):
  1402. cur_language = translation.get_language()
  1403. try:
  1404. translation.activate(language)
  1405. text = translation.gettext("welcome")
  1406. finally:
  1407. translation.activate(cur_language)
  1408. return text
  1409. Calling this function with the value ``'de'`` will give you ``"Willkommen"``,
  1410. regardless of :setting:`LANGUAGE_CODE` and language set by middleware.
  1411. Functions of particular interest are
  1412. :func:`django.utils.translation.get_language()` which returns the language used
  1413. in the current thread, :func:`django.utils.translation.activate()` which
  1414. activates a translation catalog for the current thread, and
  1415. :func:`django.utils.translation.check_for_language()`
  1416. which checks if the given language is supported by Django.
  1417. To help write more concise code, there is also a context manager
  1418. :func:`django.utils.translation.override()` that stores the current language on
  1419. enter and restores it on exit. With it, the above example becomes::
  1420. from django.utils import translation
  1421. def welcome_translated(language):
  1422. with translation.override(language):
  1423. return translation.gettext("welcome")
  1424. Language cookie
  1425. ---------------
  1426. A number of settings can be used to adjust language cookie options:
  1427. * :setting:`LANGUAGE_COOKIE_NAME`
  1428. * :setting:`LANGUAGE_COOKIE_AGE`
  1429. * :setting:`LANGUAGE_COOKIE_DOMAIN`
  1430. * :setting:`LANGUAGE_COOKIE_HTTPONLY`
  1431. * :setting:`LANGUAGE_COOKIE_PATH`
  1432. * :setting:`LANGUAGE_COOKIE_SAMESITE`
  1433. * :setting:`LANGUAGE_COOKIE_SECURE`
  1434. Implementation notes
  1435. ====================
  1436. .. _specialties-of-django-i18n:
  1437. Specialties of Django translation
  1438. ---------------------------------
  1439. Django's translation machinery uses the standard ``gettext`` module that comes
  1440. with Python. If you know ``gettext``, you might note these specialties in the
  1441. way Django does translation:
  1442. * The string domain is ``django`` or ``djangojs``. This string domain is
  1443. used to differentiate between different programs that store their data
  1444. in a common message-file library (usually ``/usr/share/locale/``). The
  1445. ``django`` domain is used for Python and template translation strings
  1446. and is loaded into the global translation catalogs. The ``djangojs``
  1447. domain is only used for JavaScript translation catalogs to make sure
  1448. that those are as small as possible.
  1449. * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
  1450. ``xgettext`` and ``msgfmt``. This is mostly for convenience.
  1451. .. _how-django-discovers-language-preference:
  1452. How Django discovers language preference
  1453. ----------------------------------------
  1454. Once you've prepared your translations -- or, if you want to use the
  1455. translations that come with Django -- you'll need to activate translation for
  1456. your app.
  1457. Behind the scenes, Django has a very flexible model of deciding which language
  1458. should be used -- installation-wide, for a particular user, or both.
  1459. To set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.
  1460. Django uses this language as the default translation -- the final attempt if no
  1461. better matching translation is found through one of the methods employed by the
  1462. locale middleware (see below).
  1463. If all you want is to run Django with your native language all you need to do
  1464. is set :setting:`LANGUAGE_CODE` and make sure the corresponding :term:`message
  1465. files <message file>` and their compiled versions (``.mo``) exist.
  1466. If you want to let each individual user specify which language they
  1467. prefer, then you also need to use the ``LocaleMiddleware``.
  1468. ``LocaleMiddleware`` enables language selection based on data from the request.
  1469. It customizes content for each user.
  1470. To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
  1471. to your :setting:`MIDDLEWARE` setting. Because middleware order matters, follow
  1472. these guidelines:
  1473. * Make sure it's one of the first middleware installed.
  1474. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
  1475. makes use of session data. And it should come before ``CommonMiddleware``
  1476. because ``CommonMiddleware`` needs an activated language in order
  1477. to resolve the requested URL.
  1478. * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
  1479. For example, your :setting:`MIDDLEWARE` might look like this::
  1480. MIDDLEWARE = [
  1481. "django.contrib.sessions.middleware.SessionMiddleware",
  1482. "django.middleware.locale.LocaleMiddleware",
  1483. "django.middleware.common.CommonMiddleware",
  1484. ]
  1485. (For more on middleware, see the :doc:`middleware documentation
  1486. </topics/http/middleware>`.)
  1487. ``LocaleMiddleware`` tries to determine the user's language preference by
  1488. following this algorithm:
  1489. * First, it looks for the language prefix in the requested URL. This is
  1490. only performed when you are using the ``i18n_patterns`` function in your
  1491. root URLconf. See :ref:`url-internationalization` for more information
  1492. about the language prefix and how to internationalize URL patterns.
  1493. * Failing that, it looks for a cookie.
  1494. The name of the cookie used is set by the :setting:`LANGUAGE_COOKIE_NAME`
  1495. setting. (The default name is ``django_language``.)
  1496. * Failing that, it looks at the ``Accept-Language`` HTTP header. This
  1497. header is sent by your browser and tells the server which language(s) you
  1498. prefer, in order by priority. Django tries each language in the header
  1499. until it finds one with available translations.
  1500. * Failing that, it uses the global :setting:`LANGUAGE_CODE` setting.
  1501. .. _locale-middleware-notes:
  1502. Notes:
  1503. * In each of these places, the language preference is expected to be in the
  1504. standard :term:`language format<language code>`, as a string. For example,
  1505. Brazilian Portuguese is ``pt-br``.
  1506. * If a base language is available but the sublanguage specified is not,
  1507. Django uses the base language. For example, if a user specifies ``de-at``
  1508. (Austrian German) but Django only has ``de`` available, Django uses
  1509. ``de``.
  1510. * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
  1511. If you want to restrict the language selection to a subset of provided
  1512. languages (because your application doesn't provide all those languages),
  1513. set :setting:`LANGUAGES` to a list of languages. For example::
  1514. LANGUAGES = [
  1515. ("de", _("German")),
  1516. ("en", _("English")),
  1517. ]
  1518. This example restricts languages that are available for automatic
  1519. selection to German and English (and any sublanguage, like ``de-ch`` or
  1520. ``en-us``).
  1521. * If you define a custom :setting:`LANGUAGES` setting, as explained in the
  1522. previous bullet, you can mark the language names as translation strings
  1523. -- but use :func:`~django.utils.translation.gettext_lazy` instead of
  1524. :func:`~django.utils.translation.gettext` to avoid a circular import.
  1525. Here's a sample settings file::
  1526. from django.utils.translation import gettext_lazy as _
  1527. LANGUAGES = [
  1528. ("de", _("German")),
  1529. ("en", _("English")),
  1530. ]
  1531. Once ``LocaleMiddleware`` determines the user's preference, it makes this
  1532. preference available as ``request.LANGUAGE_CODE`` for each
  1533. :class:`~django.http.HttpRequest`. Feel free to read this value in your view
  1534. code. Here's an example::
  1535. from django.http import HttpResponse
  1536. def hello_world(request, count):
  1537. if request.LANGUAGE_CODE == "de-at":
  1538. return HttpResponse("You prefer to read Austrian German.")
  1539. else:
  1540. return HttpResponse("You prefer to read another language.")
  1541. Note that, with static (middleware-less) translation, the language is in
  1542. ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
  1543. in ``request.LANGUAGE_CODE``.
  1544. .. _settings file: ../settings/
  1545. .. _middleware documentation: ../middleware/
  1546. .. _session: ../sessions/
  1547. .. _request object: ../request_response/#httprequest-objects
  1548. .. _how-django-discovers-translations:
  1549. How Django discovers translations
  1550. ---------------------------------
  1551. At runtime, Django builds an in-memory unified catalog of literals-translations.
  1552. To achieve this it looks for translations by following this algorithm regarding
  1553. the order in which it examines the different file paths to load the compiled
  1554. :term:`message files <message file>` (``.mo``) and the precedence of multiple
  1555. translations for the same literal:
  1556. #. The directories listed in :setting:`LOCALE_PATHS` have the highest
  1557. precedence, with the ones appearing first having higher precedence than
  1558. the ones appearing later.
  1559. #. Then, it looks for and uses if it exists a ``locale`` directory in each
  1560. of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
  1561. appearing first have higher precedence than the ones appearing later.
  1562. #. Finally, the Django-provided base translation in :source:`django/conf/locale`
  1563. is used as a fallback.
  1564. .. seealso::
  1565. The translations for literals included in JavaScript assets are looked up
  1566. following a similar but not identical algorithm. See
  1567. :class:`.JavaScriptCatalog` for more details.
  1568. You can also put :ref:`custom format files <custom-format-files>` in the
  1569. :setting:`LOCALE_PATHS` directories if you also set
  1570. :setting:`FORMAT_MODULE_PATH`.
  1571. In all cases the name of the directory containing the translation is expected to
  1572. be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, ``es_AR``,
  1573. etc. Untranslated strings for territorial language variants use the translations
  1574. of the generic language. For example, untranslated ``pt_BR`` strings use ``pt``
  1575. translations.
  1576. This way, you can write applications that include their own translations, and
  1577. you can override base translations in your project. Or, you can build a big
  1578. project out of several apps and put all translations into one big common
  1579. message file specific to the project you are composing. The choice is yours.
  1580. All message file repositories are structured the same way. They are:
  1581. * All paths listed in :setting:`LOCALE_PATHS` in your settings file are
  1582. searched for ``<language>/LC_MESSAGES/django.(po|mo)``
  1583. * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  1584. * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
  1585. To create message files, you use the :djadmin:`django-admin makemessages <makemessages>`
  1586. tool. And you use :djadmin:`django-admin compilemessages <compilemessages>`
  1587. to produce the binary ``.mo`` files that are used by ``gettext``.
  1588. You can also run :djadmin:`django-admin compilemessages
  1589. --settings=path.to.settings <compilemessages>` to make the compiler process all
  1590. the directories in your :setting:`LOCALE_PATHS` setting.
  1591. Using a non-English base language
  1592. ---------------------------------
  1593. Django makes the general assumption that the original strings in a translatable
  1594. project are written in English. You can choose another language, but you must be
  1595. aware of certain limitations:
  1596. * ``gettext`` only provides two plural forms for the original messages, so you
  1597. will also need to provide a translation for the base language to include all
  1598. plural forms if the plural rules for the base language are different from
  1599. English.
  1600. * When an English variant is activated and English strings are missing, the
  1601. fallback language will not be the :setting:`LANGUAGE_CODE` of the project,
  1602. but the original strings. For example, an English user visiting a site with
  1603. :setting:`LANGUAGE_CODE` set to Spanish and original strings written in
  1604. Russian will see Russian text rather than Spanish.