translation.txt 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  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. Another feature ``{% blocktrans %}`` supports is the ``trimmed`` option. This
  493. option will remove newline characters from the beginning and the end of the
  494. content of the ``{% blocktrans %}`` tag, replace any whitespace at the beginning
  495. and end of a line and merge all lines into one using a space character to
  496. separate them. This is quite useful for indenting the content of a ``{%
  497. blocktrans %}`` tag without having the indentation characters end up in the
  498. corresponding entry in the PO file, which makes the translation process easier.
  499. For instance, the following ``{% blocktrans %}`` tag::
  500. {% blocktrans trimmed %}
  501. First sentence.
  502. Second paragraph.
  503. {% endblocktrans %}
  504. will result in the entry ``"First sentence. Second paragraph."`` in the PO file,
  505. compared to ``"\n First sentence.\n Second sentence.\n"``, if the ``trimmed``
  506. option had not been specified.
  507. .. versionchanged:: 1.7
  508. The ``trimmed`` option was added.
  509. String literals passed to tags and filters
  510. ------------------------------------------
  511. You can translate string literals passed as arguments to tags and filters
  512. by using the familiar ``_()`` syntax::
  513. {% some_tag _("Page not found") value|yesno:_("yes,no") %}
  514. In this case, both the tag and the filter will see the translated string,
  515. so they don't need to be aware of translations.
  516. .. note::
  517. In this example, the translation infrastructure will be passed the string
  518. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  519. translated string will need to contain the comma so that the filter
  520. parsing code knows how to split up the arguments. For example, a German
  521. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  522. (keeping the comma intact).
  523. .. _translator-comments-in-templates:
  524. Comments for translators in templates
  525. -------------------------------------
  526. Just like with :ref:`Python code <translator-comments>`, these notes for
  527. translators can be specified using comments, either with the :ttag:`comment`
  528. tag:
  529. .. code-block:: html+django
  530. {% comment %}Translators: View verb{% endcomment %}
  531. {% trans "View" %}
  532. {% comment %}Translators: Short intro blurb{% endcomment %}
  533. <p>{% blocktrans %}A multiline translatable
  534. literal.{% endblocktrans %}</p>
  535. or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:
  536. .. code-block:: html+django
  537. {# Translators: Label of a button that triggers search #}
  538. <button type="submit">{% trans "Go" %}</button>
  539. {# Translators: This is a text of the base template #}
  540. {% blocktrans %}Ambiguous translatable block of text{% endblocktrans %}
  541. .. note:: Just for completeness, these are the corresponding fragments of the
  542. resulting ``.po`` file:
  543. .. code-block:: po
  544. #. Translators: View verb
  545. # path/to/template/file.html:10
  546. msgid "View"
  547. msgstr ""
  548. #. Translators: Short intro blurb
  549. # path/to/template/file.html:13
  550. msgid ""
  551. "A multiline translatable"
  552. "literal."
  553. msgstr ""
  554. # ...
  555. #. Translators: Label of a button that triggers search
  556. # path/to/template/file.html:100
  557. msgid "Go"
  558. msgstr ""
  559. #. Translators:
  560. # path/to/template/file.html:103
  561. msgid "Ambiguous translatable block of text"
  562. msgstr ""
  563. .. templatetag:: language
  564. Switching language in templates
  565. -------------------------------
  566. If you want to select a language within a template, you can use the
  567. ``language`` template tag:
  568. .. code-block:: html+django
  569. {% load i18n %}
  570. {% get_current_language as LANGUAGE_CODE %}
  571. <!-- Current language: {{ LANGUAGE_CODE }} -->
  572. <p>{% trans "Welcome to our page" %}</p>
  573. {% language 'en' %}
  574. {% get_current_language as LANGUAGE_CODE %}
  575. <!-- Current language: {{ LANGUAGE_CODE }} -->
  576. <p>{% trans "Welcome to our page" %}</p>
  577. {% endlanguage %}
  578. While the first occurrence of "Welcome to our page" uses the current language,
  579. the second will always be in English.
  580. .. _template-translation-vars:
  581. Other tags
  582. ----------
  583. Each ``RequestContext`` has access to three translation-specific variables:
  584. * ``LANGUAGES`` is a list of tuples in which the first element is the
  585. :term:`language code` and the second is the language name (translated into
  586. the currently active locale).
  587. * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
  588. Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`.)
  589. * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
  590. right-to-left language, e.g.: Hebrew, Arabic. If False it's a
  591. left-to-right language, e.g.: English, French, German etc.
  592. If you don't use the ``RequestContext`` extension, you can get those values with
  593. three tags::
  594. {% get_current_language as LANGUAGE_CODE %}
  595. {% get_available_languages as LANGUAGES %}
  596. {% get_current_language_bidi as LANGUAGE_BIDI %}
  597. These tags also require a ``{% load i18n %}``.
  598. You can also retrieve information about any of the available languages using
  599. provided template tags and filters. To get information about a single language,
  600. use the ``{% get_language_info %}`` tag::
  601. {% get_language_info for LANGUAGE_CODE as lang %}
  602. {% get_language_info for "pl" as lang %}
  603. You can then access the information::
  604. Language code: {{ lang.code }}<br />
  605. Name of language: {{ lang.name_local }}<br />
  606. Name in English: {{ lang.name }}<br />
  607. Bi-directional: {{ lang.bidi }}
  608. You can also use the ``{% get_language_info_list %}`` template tag to retrieve
  609. information for a list of languages (e.g. active languages as specified in
  610. :setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
  611. view <set_language-redirect-view>` for an example of how to display a language
  612. selector using ``{% get_language_info_list %}``.
  613. In addition to :setting:`LANGUAGES` style nested tuples,
  614. ``{% get_language_info_list %}`` supports simple lists of language codes.
  615. If you do this in your view:
  616. .. code-block:: python
  617. return render_to_response('mytemplate.html', {
  618. 'available_languages': ['en', 'es', 'fr'],
  619. }, RequestContext(request))
  620. you can iterate over those languages in the template::
  621. {% get_language_info_list for available_languages as langs %}
  622. {% for lang in langs %} ... {% endfor %}
  623. There are also simple filters available for convenience:
  624. * ``{{ LANGUAGE_CODE|language_name }}`` ("German")
  625. * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
  626. * ``{{ LANGUAGE_CODE|bidi }}`` (False)
  627. .. _Django templates: ../templates_python/
  628. Internationalization: in JavaScript code
  629. ========================================
  630. .. highlightlang:: python
  631. Adding translations to JavaScript poses some problems:
  632. * JavaScript code doesn't have access to a ``gettext`` implementation.
  633. * JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to
  634. be delivered by the server.
  635. * The translation catalogs for JavaScript should be kept as small as
  636. possible.
  637. Django provides an integrated solution for these problems: It passes the
  638. translations into JavaScript, so you can call ``gettext``, etc., from within
  639. JavaScript.
  640. .. _javascript_catalog-view:
  641. The ``javascript_catalog`` view
  642. -------------------------------
  643. .. module:: django.views.i18n
  644. .. function:: javascript_catalog(request, domain='djangojs', packages=None)
  645. The main solution to these problems is the
  646. :meth:`django.views.i18n.javascript_catalog` view, which sends out a JavaScript
  647. code library with functions that mimic the ``gettext`` interface, plus an array
  648. of translation strings. Those translation strings are taken from applications or
  649. Django core, according to what you specify in either the ``info_dict`` or the
  650. URL. Paths listed in :setting:`LOCALE_PATHS` are also included.
  651. You hook it up like this::
  652. js_info_dict = {
  653. 'packages': ('your.app.package',),
  654. }
  655. urlpatterns = patterns('',
  656. (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
  657. )
  658. Each string in ``packages`` should be in Python dotted-package syntax (the
  659. same format as the strings in :setting:`INSTALLED_APPS`) and should refer to a
  660. package that contains a ``locale`` directory. If you specify multiple packages,
  661. all those catalogs are merged into one catalog. This is useful if you have
  662. JavaScript that uses strings from different applications.
  663. The precedence of translations is such that the packages appearing later in the
  664. ``packages`` argument have higher precedence than the ones appearing at the
  665. beginning, this is important in the case of clashing translations for the same
  666. literal.
  667. By default, the view uses the ``djangojs`` gettext domain. This can be
  668. changed by altering the ``domain`` argument.
  669. You can make the view dynamic by putting the packages into the URL pattern::
  670. urlpatterns = patterns('',
  671. (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
  672. )
  673. With this, you specify the packages as a list of package names delimited by '+'
  674. signs in the URL. This is especially useful if your pages use code from
  675. different apps and this changes often and you don't want to pull in one big
  676. catalog file. As a security measure, these values can only be either
  677. ``django.conf`` or any package from the :setting:`INSTALLED_APPS` setting.
  678. The JavaScript translations found in the paths listed in the
  679. :setting:`LOCALE_PATHS` setting are also always included. To keep consistency
  680. with the translations lookup order algorithm used for Python and templates, the
  681. directories listed in :setting:`LOCALE_PATHS` have the highest precedence with
  682. the ones appearing first having higher precedence than the ones appearing
  683. later.
  684. Using the JavaScript translation catalog
  685. ----------------------------------------
  686. .. highlightlang:: javascript
  687. To use the catalog, just pull in the dynamically generated script like this:
  688. .. code-block:: html+django
  689. <script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script>
  690. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
  691. When the catalog is loaded, your JavaScript code can use the standard
  692. ``gettext`` interface to access it::
  693. document.write(gettext('this is to be translated'));
  694. There is also an ``ngettext`` interface::
  695. var object_cnt = 1 // or 0, or 2, or 3, ...
  696. s = ngettext('literal for the singular case',
  697. 'literal for the plural case', object_cnt);
  698. and even a string interpolation function::
  699. function interpolate(fmt, obj, named);
  700. The interpolation syntax is borrowed from Python, so the ``interpolate``
  701. function supports both positional and named interpolation:
  702. * Positional interpolation: ``obj`` contains a JavaScript Array object
  703. whose elements values are then sequentially interpolated in their
  704. corresponding ``fmt`` placeholders in the same order they appear.
  705. For example::
  706. fmts = ngettext('There is %s object. Remaining: %s',
  707. 'There are %s objects. Remaining: %s', 11);
  708. s = interpolate(fmts, [11, 20]);
  709. // s is 'There are 11 objects. Remaining: 20'
  710. * Named interpolation: This mode is selected by passing the optional
  711. boolean ``named`` parameter as true. ``obj`` contains a JavaScript
  712. object or associative array. For example::
  713. d = {
  714. count: 10,
  715. total: 50
  716. };
  717. fmts = ngettext('Total: %(total)s, there is %(count)s object',
  718. 'there are %(count)s of a total of %(total)s objects', d.count);
  719. s = interpolate(fmts, d, true);
  720. You shouldn't go over the top with string interpolation, though: this is still
  721. JavaScript, so the code has to make repeated regular-expression substitutions.
  722. This isn't as fast as string interpolation in Python, so keep it to those
  723. cases where you really need it (for example, in conjunction with ``ngettext``
  724. to produce proper pluralizations).
  725. Note on performance
  726. -------------------
  727. The :func:`~django.views.i18n.javascript_catalog` view generates the catalog
  728. from ``.mo`` files on every request. Since its output is constant — at least
  729. for a given version of a site — it's a good candidate for caching.
  730. Server-side caching will reduce CPU load. It's easily implemented with the
  731. :func:`~django.views.decorators.cache.cache_page` decorator. To trigger cache
  732. invalidation when your translations change, provide a version-dependent key
  733. prefix, as shown in the example below, or map the view at a version-dependent
  734. URL.
  735. .. code-block:: python
  736. from django.views.decorators.cache import cache_page
  737. from django.views.i18n import javascript_catalog
  738. # The value returned by get_version() must change when translations change.
  739. @cache_page(86400, key_prefix='js18n-%s' % get_version())
  740. def cached_javascript_catalog(request, domain='djangojs', packages=None):
  741. return javascript_catalog(request, domain, packages)
  742. Client-side caching will save bandwidth and make your site load faster. If
  743. you're using ETags (:setting:`USE_ETAGS = True <USE_ETAGS>`), you're already
  744. covered. Otherwise, you can apply :ref:`conditional decorators
  745. <conditional-decorators>`. In the following example, the cache is invalidated
  746. whenever your restart your application server.
  747. .. code-block:: python
  748. from django.utils import timezone
  749. from django.views.decorators.http import last_modified
  750. from django.views.i18n import javascript_catalog
  751. last_modified_date = timezone.now()
  752. @last_modified(lambda req, **kw: last_modified_date)
  753. def cached_javascript_catalog(request, domain='djangojs', packages=None):
  754. return javascript_catalog(request, domain, packages)
  755. You can even pre-generate the javascript catalog as part of your deployment
  756. procedure and serve it as a static file. This radical technique is implemented
  757. in django-statici18n_.
  758. .. _django-statici18n: http://django-statici18n.readthedocs.org/en/latest/
  759. .. _url-internationalization:
  760. Internationalization: in URL patterns
  761. =====================================
  762. .. module:: django.conf.urls.i18n
  763. Django provides two mechanisms to internationalize URL patterns:
  764. * Adding the language prefix to the root of the URL patterns to make it
  765. possible for :class:`~django.middleware.locale.LocaleMiddleware` to detect
  766. the language to activate from the requested URL.
  767. * Making URL patterns themselves translatable via the
  768. :func:`django.utils.translation.ugettext_lazy()` function.
  769. .. warning::
  770. Using either one of these features requires that an active language be set
  771. for each request; in other words, you need to have
  772. :class:`django.middleware.locale.LocaleMiddleware` in your
  773. :setting:`MIDDLEWARE_CLASSES` setting.
  774. Language prefix in URL patterns
  775. -------------------------------
  776. .. function:: i18n_patterns(prefix, pattern_description, ...)
  777. This function can be used in your root URLconf as a replacement for the normal
  778. :func:`django.conf.urls.patterns` function. Django will automatically
  779. prepend the current active language code to all url patterns defined within
  780. :func:`~django.conf.urls.i18n.i18n_patterns`. Example URL patterns::
  781. from django.conf.urls import patterns, include, url
  782. from django.conf.urls.i18n import i18n_patterns
  783. urlpatterns = patterns('',
  784. url(r'^sitemap\.xml$', 'sitemap.view', name='sitemap_xml'),
  785. )
  786. news_patterns = patterns('',
  787. url(r'^$', 'news.views.index', name='index'),
  788. url(r'^category/(?P<slug>[\w-]+)/$', 'news.views.category', name='category'),
  789. url(r'^(?P<slug>[\w-]+)/$', 'news.views.details', name='detail'),
  790. )
  791. urlpatterns += i18n_patterns('',
  792. url(r'^about/$', 'about.view', name='about'),
  793. url(r'^news/', include(news_patterns, namespace='news')),
  794. )
  795. After defining these URL patterns, Django will automatically add the
  796. language prefix to the URL patterns that were added by the ``i18n_patterns``
  797. function. Example::
  798. from django.core.urlresolvers import reverse
  799. from django.utils.translation import activate
  800. >>> activate('en')
  801. >>> reverse('sitemap_xml')
  802. '/sitemap.xml'
  803. >>> reverse('news:index')
  804. '/en/news/'
  805. >>> activate('nl')
  806. >>> reverse('news:detail', kwargs={'slug': 'news-slug'})
  807. '/nl/news/news-slug/'
  808. .. warning::
  809. :func:`~django.conf.urls.i18n.i18n_patterns` is only allowed in your root
  810. URLconf. Using it within an included URLconf will throw an
  811. :exc:`~django.core.exceptions.ImproperlyConfigured` exception.
  812. .. warning::
  813. Ensure that you don't have non-prefixed URL patterns that might collide
  814. with an automatically-added language prefix.
  815. Translating URL patterns
  816. ------------------------
  817. URL patterns can also be marked translatable using the
  818. :func:`~django.utils.translation.ugettext_lazy` function. Example::
  819. from django.conf.urls import patterns, include, url
  820. from django.conf.urls.i18n import i18n_patterns
  821. from django.utils.translation import ugettext_lazy as _
  822. urlpatterns = patterns(''
  823. url(r'^sitemap\.xml$', 'sitemap.view', name='sitemap_xml'),
  824. )
  825. news_patterns = patterns(''
  826. url(r'^$', 'news.views.index', name='index'),
  827. url(_(r'^category/(?P<slug>[\w-]+)/$'), 'news.views.category', name='category'),
  828. url(r'^(?P<slug>[\w-]+)/$', 'news.views.details', name='detail'),
  829. )
  830. urlpatterns += i18n_patterns('',
  831. url(_(r'^about/$'), 'about.view', name='about'),
  832. url(_(r'^news/'), include(news_patterns, namespace='news')),
  833. )
  834. After you've created the translations, the
  835. :func:`~django.core.urlresolvers.reverse` function will return the URL in the
  836. active language. Example::
  837. from django.core.urlresolvers import reverse
  838. from django.utils.translation import activate
  839. >>> activate('en')
  840. >>> reverse('news:category', kwargs={'slug': 'recent'})
  841. '/en/news/category/recent/'
  842. >>> activate('nl')
  843. >>> reverse('news:category', kwargs={'slug': 'recent'})
  844. '/nl/nieuws/categorie/recent/'
  845. .. warning::
  846. In most cases, it's best to use translated URLs only within a
  847. language-code-prefixed block of patterns (using
  848. :func:`~django.conf.urls.i18n.i18n_patterns`), to avoid the possibility
  849. that a carelessly translated URL causes a collision with a non-translated
  850. URL pattern.
  851. .. _reversing_in_templates:
  852. Reversing in templates
  853. ----------------------
  854. If localized URLs get reversed in templates they always use the current
  855. language. To link to a URL in another language use the :ttag:`language`
  856. template tag. It enables the given language in the enclosed template section:
  857. .. code-block:: html+django
  858. {% load i18n %}
  859. {% get_available_languages as languages %}
  860. {% trans "View this category in:" %}
  861. {% for lang_code, lang_name in languages %}
  862. {% language lang_code %}
  863. <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
  864. {% endlanguage %}
  865. {% endfor %}
  866. The :ttag:`language` tag expects the language code as the only argument.
  867. .. _how-to-create-language-files:
  868. Localization: how to create language files
  869. ==========================================
  870. Once the string literals of an application have been tagged for later
  871. translation, the translation themselves need to be written (or obtained). Here's
  872. how that works.
  873. Message files
  874. -------------
  875. The first step is to create a :term:`message file` for a new language. A message
  876. file is a plain-text file, representing a single language, that contains all
  877. available translation strings and how they should be represented in the given
  878. language. Message files have a ``.po`` file extension.
  879. Django comes with a tool, :djadmin:`django-admin.py makemessages
  880. <makemessages>`, that automates the creation and upkeep of these files.
  881. .. admonition:: Gettext utilities
  882. The ``makemessages`` command (and ``compilemessages`` discussed later) use
  883. commands from the GNU gettext toolset: ``xgettext``, ``msgfmt``,
  884. ``msgmerge`` and ``msguniq``.
  885. The minimum version of the ``gettext`` utilities supported is 0.15.
  886. To create or update a message file, run this command::
  887. django-admin.py makemessages -l de
  888. ...where ``de`` is the language code for the message file you want to create.
  889. The language code, in this case, is in :term:`locale format<locale name>`. For
  890. example, it's ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian
  891. German.
  892. The script should be run from one of two places:
  893. * The root directory of your Django project (the one that contains
  894. ``manage.py``).
  895. * The root directory of one of your Django apps.
  896. The script runs over your project source tree or your application source tree
  897. and pulls out all strings marked for translation (see
  898. :ref:`how-django-discovers-translations` and be sure :setting:`LOCALE_PATHS`
  899. is configured correctly). It creates (or updates) a message file in the
  900. directory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the file will be
  901. ``locale/de/LC_MESSAGES/django.po``.
  902. .. versionchanged:: 1.7
  903. When you run ``makemessages`` from the root directory of your project, the
  904. extracted strings will be automatically distributed to the proper message
  905. files. That is, a string extracted from a file of an app containing a
  906. ``locale`` directory will go in a message file under that directory.
  907. A string extracted from a file of an app without any ``locale`` directory
  908. will either go in a message file under the directory listed first in
  909. :setting:`LOCALE_PATHS` or will generate an error if :setting:`LOCALE_PATHS`
  910. is empty.
  911. By default :djadmin:`django-admin.py makemessages <makemessages>` examines every
  912. file that has the ``.html`` or ``.txt`` file extension. In case you want to
  913. override that default, use the ``--extension`` or ``-e`` option to specify the
  914. file extensions to examine::
  915. django-admin.py makemessages -l de -e txt
  916. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
  917. multiple times::
  918. django-admin.py makemessages -l de -e html,txt -e xml
  919. .. warning::
  920. When :ref:`creating message files from JavaScript source code
  921. <creating-message-files-from-js-code>` you need to use the special
  922. 'djangojs' domain, **not** ``-e js``.
  923. .. admonition:: No gettext?
  924. If you don't have the ``gettext`` utilities installed,
  925. :djadmin:`makemessages` will create empty files. If that's the case, either
  926. install the ``gettext`` utilities or just copy the English message file
  927. (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
  928. point; it's just an empty translation file.
  929. .. admonition:: Working on Windows?
  930. If you're using Windows and need to install the GNU gettext utilities so
  931. :djadmin:`makemessages` works, see :ref:`gettext_on_windows` for more
  932. information.
  933. The format of ``.po`` files is straightforward. Each ``.po`` file contains a
  934. small bit of metadata, such as the translation maintainer's contact
  935. information, but the bulk of the file is a list of **messages** -- simple
  936. mappings between translation strings and the actual translated text for the
  937. particular language.
  938. For example, if your Django app contained a translation string for the text
  939. ``"Welcome to my site."``, like so::
  940. _("Welcome to my site.")
  941. ...then :djadmin:`django-admin.py makemessages <makemessages>` will have created
  942. a ``.po`` file containing the following snippet -- a message::
  943. #: path/to/python/module.py:23
  944. msgid "Welcome to my site."
  945. msgstr ""
  946. A quick explanation:
  947. * ``msgid`` is the translation string, which appears in the source. Don't
  948. change it.
  949. * ``msgstr`` is where you put the language-specific translation. It starts
  950. out empty, so it's your responsibility to change it. Make sure you keep
  951. the quotes around your translation.
  952. * As a convenience, each message includes, in the form of a comment line
  953. prefixed with ``#`` and located above the ``msgid`` line, the filename and
  954. line number from which the translation string was gleaned.
  955. Long messages are a special case. There, the first string directly after the
  956. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
  957. written over the next few lines as one string per line. Those strings are
  958. directly concatenated. Don't forget trailing spaces within the strings;
  959. otherwise, they'll be tacked together without whitespace!
  960. .. admonition:: Mind your charset
  961. When creating a PO file with your favorite text editor, first edit
  962. the charset line (search for ``"CHARSET"``) and set it to the charset
  963. you'll be using to edit the content. Due to the way the ``gettext`` tools
  964. work internally and because we want to allow non-ASCII source strings in
  965. Django's core and your applications, you **must** use UTF-8 as the encoding
  966. for your PO file. This means that everybody will be using the same
  967. encoding, which is important when Django processes the PO files.
  968. To reexamine all source code and templates for new translation strings and
  969. update all message files for **all** languages, run this::
  970. django-admin.py makemessages -a
  971. Compiling message files
  972. -----------------------
  973. After you create your message file -- and each time you make changes to it --
  974. you'll need to compile it into a more efficient form, for use by ``gettext``. Do
  975. this with the :djadmin:`django-admin.py compilemessages <compilemessages>`
  976. utility.
  977. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
  978. are binary files optimized for use by ``gettext``. In the same directory from
  979. which you ran :djadmin:`django-admin.py makemessages <makemessages>`, run :djadmin:`django-admin.py compilemessages <compilemessages>` like this::
  980. django-admin.py compilemessages
  981. That's it. Your translations are ready for use.
  982. .. admonition:: Working on Windows?
  983. If you're using Windows and need to install the GNU gettext utilities so
  984. :djadmin:`django-admin.py compilemessages <compilemessages>` works see
  985. :ref:`gettext_on_windows` for more information.
  986. .. admonition:: .po files: Encoding and BOM usage.
  987. Django only supports ``.po`` files encoded in UTF-8 and without any BOM
  988. (Byte Order Mark) so if your text editor adds such marks to the beginning of
  989. files by default then you will need to reconfigure it.
  990. .. _creating-message-files-from-js-code:
  991. Creating message files from JavaScript source code
  992. --------------------------------------------------
  993. You create and update the message files the same way as the other Django message
  994. files -- with the :djadmin:`django-admin.py makemessages <makemessages>` tool.
  995. The only difference is you need to explicitly specify what in gettext parlance
  996. is known as a domain in this case the ``djangojs`` domain, by providing a ``-d
  997. djangojs`` parameter, like this::
  998. django-admin.py makemessages -d djangojs -l de
  999. This would create or update the message file for JavaScript for German. After
  1000. updating message files, just run :djadmin:`django-admin.py compilemessages
  1001. <compilemessages>` the same way as you do with normal Django message files.
  1002. .. _gettext_on_windows:
  1003. ``gettext`` on Windows
  1004. ----------------------
  1005. This is only needed for people who either want to extract message IDs or compile
  1006. message files (``.po``). Translation work itself just involves editing existing
  1007. files of this type, but if you want to create your own message files, or want to
  1008. test or compile a changed message file, you will need the ``gettext`` utilities:
  1009. * Download the following zip files from the GNOME servers
  1010. http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/ or from one
  1011. of its mirrors_
  1012. * ``gettext-runtime-X.zip``
  1013. * ``gettext-tools-X.zip``
  1014. ``X`` is the version number, we are requiring ``0.15`` or higher.
  1015. * Extract the contents of the ``bin\`` directories in both files to the
  1016. same folder on your system (i.e. ``C:\Program Files\gettext-utils``)
  1017. * Update the system PATH:
  1018. * ``Control Panel > System > Advanced > Environment Variables``.
  1019. * In the ``System variables`` list, click ``Path``, click ``Edit``.
  1020. * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
  1021. ``Variable value`` field.
  1022. .. _mirrors: http://ftp.gnome.org/pub/GNOME/MIRRORS
  1023. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
  1024. the ``xgettext --version`` command works properly. Do not attempt to use Django
  1025. translation utilities with a ``gettext`` package if the command ``xgettext
  1026. --version`` entered at a Windows command prompt causes a popup window saying
  1027. "xgettext.exe has generated errors and will be closed by Windows".
  1028. Miscellaneous
  1029. =============
  1030. .. _set_language-redirect-view:
  1031. The ``set_language`` redirect view
  1032. ----------------------------------
  1033. .. highlightlang:: python
  1034. .. currentmodule:: django.views.i18n
  1035. .. function:: set_language(request)
  1036. As a convenience, Django comes with a view, :func:`django.views.i18n.set_language`,
  1037. that sets a user's language preference and redirects to a given URL or, by default,
  1038. back to the previous page.
  1039. Make sure that the following item is in your
  1040. :setting:`TEMPLATE_CONTEXT_PROCESSORS` list in your settings file::
  1041. 'django.core.context_processors.i18n'
  1042. Activate this view by adding the following line to your URLconf::
  1043. (r'^i18n/', include('django.conf.urls.i18n')),
  1044. (Note that this example makes the view available at ``/i18n/setlang/``.)
  1045. .. warning::
  1046. Make sure that you don't include the above URL within
  1047. :func:`~django.conf.urls.i18n.i18n_patterns` - it needs to be
  1048. language-independent itself to work correctly.
  1049. The view expects to be called via the ``POST`` method, with a ``language``
  1050. parameter set in request. If session support is enabled, the view
  1051. saves the language choice in the user's session. Otherwise, it saves the
  1052. language choice in a cookie that is by default named ``django_language``.
  1053. (The name can be changed through the :setting:`LANGUAGE_COOKIE_NAME` setting.)
  1054. After setting the language choice, Django redirects the user, following this
  1055. algorithm:
  1056. * Django looks for a ``next`` parameter in the ``POST`` data.
  1057. * If that doesn't exist, or is empty, Django tries the URL in the
  1058. ``Referrer`` header.
  1059. * If that's empty -- say, if a user's browser suppresses that header --
  1060. then the user will be redirected to ``/`` (the site root) as a fallback.
  1061. Here's example HTML template code:
  1062. .. code-block:: html+django
  1063. <form action="{% url 'set_language' %}" method="post">
  1064. {% csrf_token %}
  1065. <input name="next" type="hidden" value="{{ redirect_to }}" />
  1066. <select name="language">
  1067. {% get_language_info_list for LANGUAGES as languages %}
  1068. {% for language in languages %}
  1069. <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
  1070. {{ language.name_local }} ({{ language.code }})
  1071. </option>
  1072. {% endfor %}
  1073. </select>
  1074. <input type="submit" value="Go" />
  1075. </form>
  1076. In this example, Django looks up the URL of the page to which the user will be
  1077. redirected in the ``redirect_to`` context variable.
  1078. Using translations outside views and templates
  1079. ----------------------------------------------
  1080. While Django provides a rich set of i18n tools for use in views and templates,
  1081. it does not restrict the usage to Django-specific code. The Django translation
  1082. mechanisms can be used to translate arbitrary texts to any language that is
  1083. supported by Django (as long as an appropriate translation catalog exists, of
  1084. course). You can load a translation catalog, activate it and translate text to
  1085. language of your choice, but remember to switch back to original language, as
  1086. activating a translation catalog is done on per-thread basis and such change
  1087. will affect code running in the same thread.
  1088. For example::
  1089. from django.utils import translation
  1090. def welcome_translated(language):
  1091. cur_language = translation.get_language()
  1092. try:
  1093. translation.activate(language)
  1094. text = translation.ugettext('welcome')
  1095. finally:
  1096. translation.activate(cur_language)
  1097. return text
  1098. Calling this function with the value 'de' will give you ``"Willkommen"``,
  1099. regardless of :setting:`LANGUAGE_CODE` and language set by middleware.
  1100. Functions of particular interest are ``django.utils.translation.get_language()``
  1101. which returns the language used in the current thread,
  1102. ``django.utils.translation.activate()`` which activates a translation catalog
  1103. for the current thread, and ``django.utils.translation.check_for_language()``
  1104. which checks if the given language is supported by Django.
  1105. Implementation notes
  1106. ====================
  1107. .. _specialties-of-django-i18n:
  1108. Specialties of Django translation
  1109. ---------------------------------
  1110. Django's translation machinery uses the standard ``gettext`` module that comes
  1111. with Python. If you know ``gettext``, you might note these specialties in the
  1112. way Django does translation:
  1113. * The string domain is ``django`` or ``djangojs``. This string domain is
  1114. used to differentiate between different programs that store their data
  1115. in a common message-file library (usually ``/usr/share/locale/``). The
  1116. ``django`` domain is used for python and template translation strings
  1117. and is loaded into the global translation catalogs. The ``djangojs``
  1118. domain is only used for JavaScript translation catalogs to make sure
  1119. that those are as small as possible.
  1120. * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
  1121. ``xgettext`` and ``msgfmt``. This is mostly for convenience.
  1122. .. _how-django-discovers-language-preference:
  1123. How Django discovers language preference
  1124. ----------------------------------------
  1125. Once you've prepared your translations -- or, if you just want to use the
  1126. translations that come with Django -- you'll just need to activate translation
  1127. for your app.
  1128. Behind the scenes, Django has a very flexible model of deciding which language
  1129. should be used -- installation-wide, for a particular user, or both.
  1130. To set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.
  1131. Django uses this language as the default translation -- the final attempt if no
  1132. better matching translation is found through one of the methods employed by the
  1133. locale middleware (see below).
  1134. If all you want is to run Django with your native language all you need to do
  1135. is set :setting:`LANGUAGE_CODE` and make sure the corresponding :term:`message
  1136. files <message file>` and their compiled versions (``.mo``) exist.
  1137. If you want to let each individual user specify which language they
  1138. prefer, then you also need to use use the ``LocaleMiddleware``.
  1139. ``LocaleMiddleware`` enables language selection based on data from the request.
  1140. It customizes content for each user.
  1141. To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
  1142. to your :setting:`MIDDLEWARE_CLASSES` setting. Because middleware order
  1143. matters, you should follow these guidelines:
  1144. * Make sure it's one of the first middlewares installed.
  1145. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
  1146. makes use of session data. And it should come before ``CommonMiddleware``
  1147. because ``CommonMiddleware`` needs an activated language in order
  1148. to resolve the requested URL.
  1149. * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
  1150. For example, your :setting:`MIDDLEWARE_CLASSES` might look like this::
  1151. MIDDLEWARE_CLASSES = (
  1152. 'django.contrib.sessions.middleware.SessionMiddleware',
  1153. 'django.middleware.locale.LocaleMiddleware',
  1154. 'django.middleware.common.CommonMiddleware',
  1155. )
  1156. (For more on middleware, see the :doc:`middleware documentation
  1157. </topics/http/middleware>`.)
  1158. ``LocaleMiddleware`` tries to determine the user's language preference by
  1159. following this algorithm:
  1160. * First, it looks for the language prefix in the requested URL. This is
  1161. only performed when you are using the ``i18n_patterns`` function in your
  1162. root URLconf. See :ref:`url-internationalization` for more information
  1163. about the language prefix and how to internationalize URL patterns.
  1164. * Failing that, it looks for a ``_language`` key in the current user's session.
  1165. .. versionchanged:: 1.7
  1166. In previous versions, the key was named ``django_language`` but it was
  1167. renamed to start with an underscore to denote a Django reserved session
  1168. key.
  1169. * Failing that, it looks for a cookie.
  1170. The name of the cookie used is set by the :setting:`LANGUAGE_COOKIE_NAME`
  1171. setting. (The default name is ``django_language``.)
  1172. * Failing that, it looks at the ``Accept-Language`` HTTP header. This
  1173. header is sent by your browser and tells the server which language(s) you
  1174. prefer, in order by priority. Django tries each language in the header
  1175. until it finds one with available translations.
  1176. * Failing that, it uses the global :setting:`LANGUAGE_CODE` setting.
  1177. .. _locale-middleware-notes:
  1178. Notes:
  1179. * In each of these places, the language preference is expected to be in the
  1180. standard :term:`language format<language code>`, as a string. For example,
  1181. Brazilian Portuguese is ``pt-br``.
  1182. * If a base language is available but the sublanguage specified is not,
  1183. Django uses the base language. For example, if a user specifies ``de-at``
  1184. (Austrian German) but Django only has ``de`` available, Django uses
  1185. ``de``.
  1186. * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
  1187. If you want to restrict the language selection to a subset of provided
  1188. languages (because your application doesn't provide all those languages),
  1189. set :setting:`LANGUAGES` to a list of languages. For example::
  1190. LANGUAGES = (
  1191. ('de', _('German')),
  1192. ('en', _('English')),
  1193. )
  1194. This example restricts languages that are available for automatic
  1195. selection to German and English (and any sublanguage, like de-ch or
  1196. en-us).
  1197. * If you define a custom :setting:`LANGUAGES` setting, as explained in the
  1198. previous bullet, you can mark the language names as translation strings
  1199. -- but use :func:`~django.utils.translation.ugettext_lazy` instead of
  1200. :func:`~django.utils.translation.ugettext` to avoid a circular import.
  1201. Here's a sample settings file::
  1202. from django.utils.translation import ugettext_lazy as _
  1203. LANGUAGES = (
  1204. ('de', _('German')),
  1205. ('en', _('English')),
  1206. )
  1207. Once ``LocaleMiddleware`` determines the user's preference, it makes this
  1208. preference available as ``request.LANGUAGE_CODE`` for each
  1209. :class:`~django.http.HttpRequest`. Feel free to read this value in your view
  1210. code. Here's a simple example::
  1211. from django.http import HttpResponse
  1212. def hello_world(request, count):
  1213. if request.LANGUAGE_CODE == 'de-at':
  1214. return HttpResponse("You prefer to read Austrian German.")
  1215. else:
  1216. return HttpResponse("You prefer to read another language.")
  1217. Note that, with static (middleware-less) translation, the language is in
  1218. ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
  1219. in ``request.LANGUAGE_CODE``.
  1220. .. _settings file: ../settings/
  1221. .. _middleware documentation: ../middleware/
  1222. .. _session: ../sessions/
  1223. .. _request object: ../request_response/#httprequest-objects
  1224. .. _how-django-discovers-translations:
  1225. How Django discovers translations
  1226. ---------------------------------
  1227. At runtime, Django builds an in-memory unified catalog of literals-translations.
  1228. To achieve this it looks for translations by following this algorithm regarding
  1229. the order in which it examines the different file paths to load the compiled
  1230. :term:`message files <message file>` (``.mo``) and the precedence of multiple
  1231. translations for the same literal:
  1232. 1. The directories listed in :setting:`LOCALE_PATHS` have the highest
  1233. precedence, with the ones appearing first having higher precedence than
  1234. the ones appearing later.
  1235. 2. Then, it looks for and uses if it exists a ``locale`` directory in each
  1236. of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
  1237. appearing first have higher precedence than the ones appearing later.
  1238. 3. Finally, the Django-provided base translation in ``django/conf/locale``
  1239. is used as a fallback.
  1240. .. seealso::
  1241. The translations for literals included in JavaScript assets are looked up
  1242. following a similar but not identical algorithm. See the
  1243. :ref:`javascript_catalog view documentation <javascript_catalog-view>` for
  1244. more details.
  1245. In all cases the name of the directory containing the translation is expected to
  1246. be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, ``es_AR``,
  1247. etc.
  1248. This way, you can write applications that include their own translations, and
  1249. you can override base translations in your project. Or, you can just build
  1250. a big project out of several apps and put all translations into one big common
  1251. message file specific to the project you are composing. The choice is yours.
  1252. All message file repositories are structured the same way. They are:
  1253. * All paths listed in :setting:`LOCALE_PATHS` in your settings file are
  1254. searched for ``<language>/LC_MESSAGES/django.(po|mo)``
  1255. * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  1256. * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
  1257. To create message files, you use the :djadmin:`django-admin.py makemessages <makemessages>`
  1258. tool. And you use :djadmin:`django-admin.py compilemessages <compilemessages>`
  1259. to produce the binary ``.mo`` files that are used by ``gettext``.
  1260. You can also run :djadmin:`django-admin.py compilemessages
  1261. --settings=path.to.settings <compilemessages>` to make the compiler process all
  1262. the directories in your :setting:`LOCALE_PATHS` setting.