translation.txt 68 KB

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