translation.txt 66 KB

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