translation.txt 77 KB

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