translation.txt 65 KB

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