translation.txt 77 KB

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