translation.txt 67 KB

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