translation.txt 59 KB

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