translation.txt 77 KB

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