translation.txt 80 KB

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