internationalization.txt 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. .. _topics-i18n-internationalization:
  2. ====================
  3. Internationalization
  4. ====================
  5. Overview
  6. ========
  7. The goal of internationalization is to allow a single Web application to offer
  8. its content and functionality in multiple languages and locales.
  9. For text translations, you, the Django developer, can accomplish this goal by
  10. adding a minimal amount of hooks to your Python and templates. These hooks
  11. are called **translation strings**. They tell Django: "This text should be
  12. translated into the end user's language, if a translation for this text is
  13. available in that language." It's your responsibility to mark translatable
  14. strings; the system can only translate strings it knows about.
  15. Django takes care of using these hooks to translate Web apps, on the fly,
  16. according to users' language preferences.
  17. Specifying translation strings: In Python code
  18. ==============================================
  19. Standard translation
  20. --------------------
  21. Specify a translation string by using the function ``ugettext()``. It's
  22. convention to import this as a shorter alias, ``_``, to save typing.
  23. .. note::
  24. Python's standard library ``gettext`` module installs ``_()`` into the
  25. global namespace, as an alias for ``gettext()``. In Django, we have chosen
  26. not to follow this practice, for a couple of reasons:
  27. 1. For international character set (Unicode) support, ``ugettext()`` is
  28. more useful than ``gettext()``. Sometimes, you should be using
  29. ``ugettext_lazy()`` as the default translation method for a particular
  30. file. Without ``_()`` in the global namespace, the developer has to
  31. think about which is the most appropriate translation function.
  32. 2. The underscore character (``_``) is used to represent "the previous
  33. result" in Python's interactive shell and doctest tests. Installing a
  34. global ``_()`` function causes interference. Explicitly importing
  35. ``ugettext()`` as ``_()`` avoids this problem.
  36. .. highlightlang:: python
  37. In this example, the text ``"Welcome to my site."`` is marked as a translation
  38. string::
  39. from django.utils.translation import ugettext as _
  40. def my_view(request):
  41. output = _("Welcome to my site.")
  42. return HttpResponse(output)
  43. Obviously, you could code this without using the alias. This example is
  44. identical to the previous one::
  45. from django.utils.translation import ugettext
  46. def my_view(request):
  47. output = ugettext("Welcome to my site.")
  48. return HttpResponse(output)
  49. Translation works on computed values. This example is identical to the previous
  50. two::
  51. def my_view(request):
  52. words = ['Welcome', 'to', 'my', 'site.']
  53. output = _(' '.join(words))
  54. return HttpResponse(output)
  55. Translation works on variables. Again, here's an identical example::
  56. def my_view(request):
  57. sentence = 'Welcome to my site.'
  58. output = _(sentence)
  59. return HttpResponse(output)
  60. (The caveat with using variables or computed values, as in the previous two
  61. examples, is that Django's translation-string-detecting utility,
  62. ``django-admin.py makemessages``, won't be able to find these strings. More on
  63. ``makemessages`` later.)
  64. The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
  65. specified with Python's standard named-string interpolation syntax. Example::
  66. def my_view(request, m, d):
  67. output = _('Today is %(month)s, %(day)s.') % {'month': m, 'day': d}
  68. return HttpResponse(output)
  69. This technique lets language-specific translations reorder the placeholder
  70. text. For example, an English translation may be ``"Today is November, 26."``,
  71. while a Spanish translation may be ``"Hoy es 26 de Noviembre."`` -- with the
  72. placeholders (the month and the day) with their positions swapped.
  73. For this reason, you should use named-string interpolation (e.g., ``%(day)s``)
  74. instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
  75. have more than a single parameter. If you used positional interpolation,
  76. translations wouldn't be able to reorder placeholder text.
  77. Marking strings as no-op
  78. ------------------------
  79. Use the function ``django.utils.translation.ugettext_noop()`` to mark a string
  80. as a translation string without translating it. The string is later translated
  81. from a variable.
  82. Use this if you have constant strings that should be stored in the source
  83. language because they are exchanged over systems or users -- such as strings in
  84. a database -- but should be translated at the last possible point in time, such
  85. as when the string is presented to the user.
  86. Pluralization
  87. -------------
  88. Use the function ``django.utils.translation.ungettext()`` to specify pluralized
  89. messages.
  90. ``ungettext`` takes three arguments: the singular translation string, the plural
  91. translation string and the number of objects.
  92. This function is useful when you need your Django application to be localizable
  93. to languages where the number and complexity of `plural forms
  94. <http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
  95. greater than the two forms used in English ('object' for the singular and
  96. 'objects' for all the cases where ``count`` is different from zero, irrespective
  97. of its value.)
  98. For example::
  99. from django.utils.translation import ungettext
  100. def hello_world(request, count):
  101. page = ungettext('there is %(count)d object', 'there are %(count)d objects', count) % {
  102. 'count': count,
  103. }
  104. return HttpResponse(page)
  105. In this example the number of objects is passed to the translation languages as
  106. the ``count`` variable.
  107. Lets see a slightly more complex usage example::
  108. from django.utils.translation import ungettext
  109. count = Report.objects.count()
  110. if count == 1:
  111. name = Report._meta.verbose_name
  112. else:
  113. name = Report._meta.verbose_name_plural
  114. text = ungettext(
  115. 'There is %(count)d %(name)s available.',
  116. 'There are %(count)d %(name)s available.',
  117. count
  118. ) % {
  119. 'count': count,
  120. 'name': name
  121. }
  122. Here we reuse localizable, hopefully already translated literals (contained in
  123. the ``verbose_name`` and ``verbose_name_plural`` model ``Meta`` options) for
  124. other parts of the sentence so all of it is consistently based on the
  125. cardinality of the elements at play.
  126. .. _pluralization-var-notes:
  127. .. note::
  128. When using this technique, make sure you use a single name for every
  129. extrapolated variable included in the literal. In the example above note how
  130. we used the ``name`` Python variable in both translation strings. This
  131. example would fail::
  132. from django.utils.translation import ungettext
  133. from myapp.models import Report
  134. count = Report.objects.count()
  135. d = {
  136. 'count': count,
  137. 'name': Report._meta.verbose_name
  138. 'plural_name': Report._meta.verbose_name_plural
  139. }
  140. text = ungettext(
  141. 'There is %(count)d %(name)s available.',
  142. 'There are %(count)d %(plural_name)s available.',
  143. count
  144. ) % d
  145. You would get a ``a format specification for argument 'name', as in
  146. 'msgstr[0]', doesn't exist in 'msgid'`` error when running
  147. ``django-admin.py compilemessages`` or a ``KeyError`` Python exception at
  148. runtime.
  149. .. _lazy-translations:
  150. Lazy translation
  151. ----------------
  152. Use the function ``django.utils.translation.ugettext_lazy()`` to translate
  153. strings lazily -- when the value is accessed rather than when the
  154. ``ugettext_lazy()`` function is called.
  155. For example, to translate a model's ``help_text``, do the following::
  156. from django.utils.translation import ugettext_lazy
  157. class MyThing(models.Model):
  158. name = models.CharField(help_text=ugettext_lazy('This is the help text'))
  159. In this example, ``ugettext_lazy()`` stores a lazy reference to the string --
  160. not the actual translation. The translation itself will be done when the string
  161. is used in a string context, such as template rendering on the Django admin
  162. site.
  163. The result of a ``ugettext_lazy()`` call can be used wherever you would use a
  164. unicode string (an object with type ``unicode``) in Python. If you try to use
  165. it where a bytestring (a ``str`` object) is expected, things will not work as
  166. expected, since a ``ugettext_lazy()`` object doesn't know how to convert
  167. itself to a bytestring. You can't use a unicode string inside a bytestring,
  168. either, so this is consistent with normal Python behavior. For example::
  169. # This is fine: putting a unicode proxy into a unicode string.
  170. u"Hello %s" % ugettext_lazy("people")
  171. # This will not work, since you cannot insert a unicode object
  172. # into a bytestring (nor can you insert our unicode proxy there)
  173. "Hello %s" % ugettext_lazy("people")
  174. If you ever see output that looks like ``"hello
  175. <django.utils.functional...>"``, you have tried to insert the result of
  176. ``ugettext_lazy()`` into a bytestring. That's a bug in your code.
  177. If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
  178. ``_`` (underscore), like so::
  179. from django.utils.translation import ugettext_lazy as _
  180. class MyThing(models.Model):
  181. name = models.CharField(help_text=_('This is the help text'))
  182. Always use lazy translations in :ref:`Django models <topics-db-models>`.
  183. Field names and table names should be marked for translation (otherwise, they
  184. won't be translated in the admin interface). This means writing explicit
  185. ``verbose_name`` and ``verbose_name_plural`` options in the ``Meta`` class,
  186. though, rather than relying on Django's default determination of
  187. ``verbose_name`` and ``verbose_name_plural`` by looking at the model's class
  188. name::
  189. from django.utils.translation import ugettext_lazy as _
  190. class MyThing(models.Model):
  191. name = models.CharField(_('name'), help_text=_('This is the help text'))
  192. class Meta:
  193. verbose_name = _('my thing')
  194. verbose_name_plural = _('mythings')
  195. Working with lazy translation objects
  196. -------------------------------------
  197. .. highlightlang:: python
  198. Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
  199. and utility functions is a common operation. When you're working with these
  200. objects elsewhere in your code, you should ensure that you don't accidentally
  201. convert them to strings, because they should be converted as late as possible
  202. (so that the correct locale is in effect). This necessitates the use of a
  203. couple of helper functions.
  204. Joining strings: string_concat()
  205. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  206. Standard Python string joins (``''.join([...])``) will not work on lists
  207. containing lazy translation objects. Instead, you can use
  208. ``django.utils.translation.string_concat()``, which creates a lazy object that
  209. concatenates its contents *and* converts them to strings only when the result
  210. is included in a string. For example::
  211. from django.utils.translation import string_concat
  212. ...
  213. name = ugettext_lazy(u'John Lennon')
  214. instrument = ugettext_lazy(u'guitar')
  215. result = string_concat([name, ': ', instrument])
  216. In this case, the lazy translations in ``result`` will only be converted to
  217. strings when ``result`` itself is used in a string (usually at template
  218. rendering time).
  219. The allow_lazy() decorator
  220. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  221. Django offers many utility functions (particularly in ``django.utils``) that
  222. take a string as their first argument and do something to that string. These
  223. functions are used by template filters as well as directly in other code.
  224. If you write your own similar functions and deal with translations, you'll
  225. face the problem of what to do when the first argument is a lazy translation
  226. object. You don't want to convert it to a string immediately, because you might
  227. be using this function outside of a view (and hence the current thread's locale
  228. setting will not be correct).
  229. For cases like this, use the ``django.utils.functional.allow_lazy()``
  230. decorator. It modifies the function so that *if* it's called with a lazy
  231. translation as the first argument, the function evaluation is delayed until it
  232. needs to be converted to a string.
  233. For example::
  234. from django.utils.functional import allow_lazy
  235. def fancy_utility_function(s, ...):
  236. # Do some conversion on string 's'
  237. ...
  238. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  239. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  240. a number of extra arguments (``*args``) specifying the type(s) that the
  241. original function can return. Usually, it's enough to include ``unicode`` here
  242. and ensure that your function returns only Unicode strings.
  243. Using this decorator means you can write your function and assume that the
  244. input is a proper string, then add support for lazy translation objects at the
  245. end.
  246. Specifying translation strings: In template code
  247. ================================================
  248. .. highlightlang:: html+django
  249. Translations in :ref:`Django templates <topics-templates>` uses two template
  250. tags and a slightly different syntax than in Python code. To give your template
  251. access to these tags, put ``{% load i18n %}`` toward the top of your template.
  252. The ``{% trans %}`` template tag translates either a constant string
  253. (enclosed in single or double quotes) or variable content::
  254. <title>{% trans "This is the title." %}</title>
  255. <title>{% trans myvar %}</title>
  256. If the ``noop`` option is present, variable lookup still takes place but the
  257. translation is skipped. This is useful when "stubbing out" content that will
  258. require translation in the future::
  259. <title>{% trans "myvar" noop %}</title>
  260. Internally, inline translations use an ``ugettext`` call.
  261. It's not possible to mix a template variable inside a string within ``{% trans
  262. %}``. If your translations require strings with variables (placeholders), use
  263. ``{% blocktrans %}``::
  264. {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
  265. To translate a template expression -- say, using template filters -- you need
  266. to bind the expression to a local variable for use within the translation
  267. block::
  268. {% blocktrans with value|filter as myvar %}
  269. This will have {{ myvar }} inside.
  270. {% endblocktrans %}
  271. If you need to bind more than one expression inside a ``blocktrans`` tag,
  272. separate the pieces with ``and``::
  273. {% blocktrans with book|title as book_t and author|title as author_t %}
  274. This is {{ book_t }} by {{ author_t }}
  275. {% endblocktrans %}
  276. To pluralize, specify both the singular and plural forms with the
  277. ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
  278. ``{% endblocktrans %}``. Example::
  279. {% blocktrans count list|length as counter %}
  280. There is only one {{ name }} object.
  281. {% plural %}
  282. There are {{ counter }} {{ name }} objects.
  283. {% endblocktrans %}
  284. When you use the pluralization feature and bind additional values to local
  285. variables apart from the counter value that selects the translated literal to be
  286. used, have in mind that the ``blocktrans`` construct is internally converted
  287. to an ``ungettext`` call. This means the same :ref:`notes regarding ungettext
  288. variables <pluralization-var-notes>` apply.
  289. Each ``RequestContext`` has access to three translation-specific variables:
  290. * ``LANGUAGES`` is a list of tuples in which the first element is the
  291. :term:`language code` and the second is the language name (translated into
  292. the currently active locale).
  293. * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
  294. Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`.)
  295. * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
  296. right-to-left language, e.g.: Hebrew, Arabic. If False it's a
  297. left-to-right language, e.g.: English, French, German etc.
  298. If you don't use the ``RequestContext`` extension, you can get those values with
  299. three tags::
  300. {% get_current_language as LANGUAGE_CODE %}
  301. {% get_available_languages as LANGUAGES %}
  302. {% get_current_language_bidi as LANGUAGE_BIDI %}
  303. These tags also require a ``{% load i18n %}``.
  304. Translation hooks are also available within any template block tag that accepts
  305. constant strings. In those cases, just use ``_()`` syntax to specify a
  306. translation string::
  307. {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
  308. In this case, both the tag and the filter will see the already-translated
  309. string, so they don't need to be aware of translations.
  310. .. note::
  311. In this example, the translation infrastructure will be passed the string
  312. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  313. translated string will need to contain the comma so that the filter
  314. parsing code knows how to split up the arguments. For example, a German
  315. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  316. (keeping the comma intact).
  317. .. _Django templates: ../templates_python/
  318. Specifying translation strings: In JavaScript code
  319. ==================================================
  320. Adding translations to JavaScript poses some problems:
  321. * JavaScript code doesn't have access to a ``gettext`` implementation.
  322. * JavaScript code doesn't have access to .po or .mo files; they need to be
  323. delivered by the server.
  324. * The translation catalogs for JavaScript should be kept as small as
  325. possible.
  326. Django provides an integrated solution for these problems: It passes the
  327. translations into JavaScript, so you can call ``gettext``, etc., from within
  328. JavaScript.
  329. The ``javascript_catalog`` view
  330. -------------------------------
  331. The main solution to these problems is the ``javascript_catalog`` view, which
  332. sends out a JavaScript code library with functions that mimic the ``gettext``
  333. interface, plus an array of translation strings. Those translation strings are
  334. taken from the application, project or Django core, according to what you
  335. specify in either the info_dict or the URL.
  336. You hook it up like this::
  337. js_info_dict = {
  338. 'packages': ('your.app.package',),
  339. }
  340. urlpatterns = patterns('',
  341. (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
  342. )
  343. Each string in ``packages`` should be in Python dotted-package syntax (the
  344. same format as the strings in ``INSTALLED_APPS``) and should refer to a package
  345. that contains a ``locale`` directory. If you specify multiple packages, all
  346. those catalogs are merged into one catalog. This is useful if you have
  347. JavaScript that uses strings from different applications.
  348. You can make the view dynamic by putting the packages into the URL pattern::
  349. urlpatterns = patterns('',
  350. (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
  351. )
  352. With this, you specify the packages as a list of package names delimited by '+'
  353. signs in the URL. This is especially useful if your pages use code from
  354. different apps and this changes often and you don't want to pull in one big
  355. catalog file. As a security measure, these values can only be either
  356. ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
  357. Using the JavaScript translation catalog
  358. ----------------------------------------
  359. To use the catalog, just pull in the dynamically generated script like this::
  360. <script type="text/javascript" src={% url django.views.i18n.javascript_catalog %}"></script>
  361. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
  362. When the catalog is loaded, your JavaScript code can use the standard
  363. ``gettext`` interface to access it::
  364. document.write(gettext('this is to be translated'));
  365. There is also an ``ngettext`` interface::
  366. var object_cnt = 1 // or 0, or 2, or 3, ...
  367. s = ngettext('literal for the singular case',
  368. 'literal for the plural case', object_cnt);
  369. and even a string interpolation function::
  370. function interpolate(fmt, obj, named);
  371. The interpolation syntax is borrowed from Python, so the ``interpolate``
  372. function supports both positional and named interpolation:
  373. * Positional interpolation: ``obj`` contains a JavaScript Array object
  374. whose elements values are then sequentially interpolated in their
  375. corresponding ``fmt`` placeholders in the same order they appear.
  376. For example::
  377. fmts = ngettext('There is %s object. Remaining: %s',
  378. 'There are %s objects. Remaining: %s', 11);
  379. s = interpolate(fmts, [11, 20]);
  380. // s is 'There are 11 objects. Remaining: 20'
  381. * Named interpolation: This mode is selected by passing the optional
  382. boolean ``named`` parameter as true. ``obj`` contains a JavaScript
  383. object or associative array. For example::
  384. d = {
  385. count: 10
  386. total: 50
  387. };
  388. fmts = ngettext('Total: %(total)s, there is %(count)s object',
  389. 'there are %(count)s of a total of %(total)s objects', d.count);
  390. s = interpolate(fmts, d, true);
  391. You shouldn't go over the top with string interpolation, though: this is still
  392. JavaScript, so the code has to make repeated regular-expression substitutions.
  393. This isn't as fast as string interpolation in Python, so keep it to those
  394. cases where you really need it (for example, in conjunction with ``ngettext``
  395. to produce proper pluralizations).
  396. The ``set_language`` redirect view
  397. ==================================
  398. As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
  399. that sets a user's language preference and redirects back to the previous page.
  400. Activate this view by adding the following line to your URLconf::
  401. (r'^i18n/', include('django.conf.urls.i18n')),
  402. (Note that this example makes the view available at ``/i18n/setlang/``.)
  403. The view expects to be called via the ``POST`` method, with a ``language``
  404. parameter set in request. If session support is enabled, the view
  405. saves the language choice in the user's session. Otherwise, it saves the
  406. language choice in a cookie that is by default named ``django_language``.
  407. (The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting.)
  408. After setting the language choice, Django redirects the user, following this
  409. algorithm:
  410. * Django looks for a ``next`` parameter in the ``POST`` data.
  411. * If that doesn't exist, or is empty, Django tries the URL in the
  412. ``Referrer`` header.
  413. * If that's empty -- say, if a user's browser suppresses that header --
  414. then the user will be redirected to ``/`` (the site root) as a fallback.
  415. Here's example HTML template code:
  416. .. code-block:: html+django
  417. <form action="/i18n/setlang/" method="post">
  418. <input name="next" type="hidden" value="/next/page/" />
  419. <select name="language">
  420. {% for lang in LANGUAGES %}
  421. <option value="{{ lang.0 }}">{{ lang.1 }}</option>
  422. {% endfor %}
  423. </select>
  424. <input type="submit" value="Go" />
  425. </form>