i18n.txt 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. .. _topics-i18n:
  2. ====================
  3. Internationalization
  4. ====================
  5. Django has full support for internationalization of text in code and templates.
  6. Here's how it works.
  7. Overview
  8. ========
  9. The goal of internationalization is to allow a single Web application to offer
  10. its content and functionality in multiple languages.
  11. You, the Django developer, can accomplish this goal by adding a minimal amount
  12. of hooks to your Python code and templates. These hooks are called
  13. **translation strings**. They tell Django: "This text should be translated into
  14. the end user's language, if a translation for this text is available in that
  15. language."
  16. Django takes care of using these hooks to translate Web apps, on the fly,
  17. according to users' language preferences.
  18. Essentially, Django does two things:
  19. * It lets developers and template authors specify which parts of their apps
  20. should be translatable.
  21. * It uses these hooks to translate Web apps for particular users according
  22. to their language preferences.
  23. If you don't need internationalization in your app
  24. ==================================================
  25. Django's internationalization hooks are on by default, and that means there's a
  26. bit of i18n-related overhead in certain places of the framework. If you don't
  27. use internationalization, you should take the two seconds to set
  28. :setting:`USE_I18N = False <USE_I18N>` in your settings file. If
  29. :setting:`USE_I18N` is set to ``False``, then Django will make some
  30. optimizations so as not to load the internationalization machinery.
  31. You'll probably also want to remove ``'django.core.context_processors.i18n'``
  32. from your ``TEMPLATE_CONTEXT_PROCESSORS`` setting.
  33. If you do need internationalization: three steps
  34. ================================================
  35. 1. Embed translation strings in your Python code and templates.
  36. 2. Get translations for those strings, in whichever languages you want to
  37. support.
  38. 3. Activate the locale middleware in your Django settings.
  39. .. admonition:: Behind the scenes
  40. Django's translation machinery uses the standard ``gettext`` module that
  41. comes with Python.
  42. 1. How to specify translation strings
  43. =====================================
  44. Translation strings specify "This text should be translated." These strings can
  45. appear in your Python code and templates. It's your responsibility to mark
  46. translatable strings; the system can only translate strings it knows about.
  47. In Python code
  48. --------------
  49. Standard translation
  50. ~~~~~~~~~~~~~~~~~~~~
  51. Specify a translation string by using the function ``ugettext()``. It's
  52. convention to import this as a shorter alias, ``_``, to save typing.
  53. .. note::
  54. Python's standard library ``gettext`` module installs ``_()`` into the
  55. global namespace, as an alias for ``gettext()``. In Django, we have chosen
  56. not to follow this practice, for a couple of reasons:
  57. 1. For international character set (Unicode) support, ``ugettext()`` is
  58. more useful than ``gettext()``. Sometimes, you should be using
  59. ``ugettext_lazy()`` as the default translation method for a particular
  60. file. Without ``_()`` in the global namespace, the developer has to
  61. think about which is the most appropriate translation function.
  62. 2. The underscore character (``_``) is used to represent "the previous
  63. result" in Python's interactive shell and doctest tests. Installing a
  64. global ``_()`` function causes interference. Explicitly importing
  65. ``ugettext()`` as ``_()`` avoids this problem.
  66. .. highlightlang:: python
  67. In this example, the text ``"Welcome to my site."`` is marked as a translation
  68. string::
  69. from django.utils.translation import ugettext as _
  70. def my_view(request):
  71. output = _("Welcome to my site.")
  72. return HttpResponse(output)
  73. Obviously, you could code this without using the alias. This example is
  74. identical to the previous one::
  75. from django.utils.translation import ugettext
  76. def my_view(request):
  77. output = ugettext("Welcome to my site.")
  78. return HttpResponse(output)
  79. Translation works on computed values. This example is identical to the previous
  80. two::
  81. def my_view(request):
  82. words = ['Welcome', 'to', 'my', 'site.']
  83. output = _(' '.join(words))
  84. return HttpResponse(output)
  85. Translation works on variables. Again, here's an identical example::
  86. def my_view(request):
  87. sentence = 'Welcome to my site.'
  88. output = _(sentence)
  89. return HttpResponse(output)
  90. (The caveat with using variables or computed values, as in the previous two
  91. examples, is that Django's translation-string-detecting utility,
  92. ``django-admin.py makemessages``, won't be able to find these strings. More on
  93. ``makemessages`` later.)
  94. The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
  95. specified with Python's standard named-string interpolation syntax. Example::
  96. def my_view(request, m, d):
  97. output = _('Today is %(month)s, %(day)s.') % {'month': m, 'day': d}
  98. return HttpResponse(output)
  99. This technique lets language-specific translations reorder the placeholder
  100. text. For example, an English translation may be ``"Today is November, 26."``,
  101. while a Spanish translation may be ``"Hoy es 26 de Noviembre."`` -- with the
  102. placeholders (the month and the day) with their positions swapped.
  103. For this reason, you should use named-string interpolation (e.g., ``%(day)s``)
  104. instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
  105. have more than a single parameter. If you used positional interpolation,
  106. translations wouldn't be able to reorder placeholder text.
  107. Marking strings as no-op
  108. ~~~~~~~~~~~~~~~~~~~~~~~~
  109. Use the function ``django.utils.translation.ugettext_noop()`` to mark a string
  110. as a translation string without translating it. The string is later translated
  111. from a variable.
  112. Use this if you have constant strings that should be stored in the source
  113. language because they are exchanged over systems or users -- such as strings in
  114. a database -- but should be translated at the last possible point in time, such
  115. as when the string is presented to the user.
  116. .. _lazy-translations:
  117. Lazy translation
  118. ~~~~~~~~~~~~~~~~
  119. Use the function ``django.utils.translation.ugettext_lazy()`` to translate
  120. strings lazily -- when the value is accessed rather than when the
  121. ``ugettext_lazy()`` function is called.
  122. For example, to translate a model's ``help_text``, do the following::
  123. from django.utils.translation import ugettext_lazy
  124. class MyThing(models.Model):
  125. name = models.CharField(help_text=ugettext_lazy('This is the help text'))
  126. In this example, ``ugettext_lazy()`` stores a lazy reference to the string --
  127. not the actual translation. The translation itself will be done when the string
  128. is used in a string context, such as template rendering on the Django admin
  129. site.
  130. The result of a ``ugettext_lazy()`` call can be used wherever you would use a
  131. unicode string (an object with type ``unicode``) in Python. If you try to use
  132. it where a bytestring (a ``str`` object) is expected, things will not work as
  133. expected, since a ``ugettext_lazy()`` object doesn't know how to convert
  134. itself to a bytestring. You can't use a unicode string inside a bytestring,
  135. either, so this is consistent with normal Python behavior. For example::
  136. # This is fine: putting a unicode proxy into a unicode string.
  137. u"Hello %s" % ugettext_lazy("people")
  138. # This will not work, since you cannot insert a unicode object
  139. # into a bytestring (nor can you insert our unicode proxy there)
  140. "Hello %s" % ugettext_lazy("people")
  141. If you ever see output that looks like ``"hello
  142. <django.utils.functional...>"``, you have tried to insert the result of
  143. ``ugettext_lazy()`` into a bytestring. That's a bug in your code.
  144. If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
  145. ``_`` (underscore), like so::
  146. from django.utils.translation import ugettext_lazy as _
  147. class MyThing(models.Model):
  148. name = models.CharField(help_text=_('This is the help text'))
  149. Always use lazy translations in :ref:`Django models <topics-db-models>`.
  150. Field names and table names should be marked for translation (otherwise, they
  151. won't be translated in the admin interface). This means writing explicit
  152. ``verbose_name`` and ``verbose_name_plural`` options in the ``Meta`` class,
  153. though, rather than relying on Django's default determination of
  154. ``verbose_name`` and ``verbose_name_plural`` by looking at the model's class
  155. name::
  156. from django.utils.translation import ugettext_lazy as _
  157. class MyThing(models.Model):
  158. name = models.CharField(_('name'), help_text=_('This is the help text'))
  159. class Meta:
  160. verbose_name = _('my thing')
  161. verbose_name_plural = _('mythings')
  162. Pluralization
  163. ~~~~~~~~~~~~~
  164. Use the function ``django.utils.translation.ungettext()`` to specify pluralized
  165. messages. Example::
  166. from django.utils.translation import ungettext
  167. def hello_world(request, count):
  168. page = ungettext('there is %(count)d object', 'there are %(count)d objects', count) % {
  169. 'count': count,
  170. }
  171. return HttpResponse(page)
  172. ``ungettext`` takes three arguments: the singular translation string, the plural
  173. translation string and the number of objects (which is passed to the
  174. translation languages as the ``count`` variable).
  175. In template code
  176. ----------------
  177. .. highlightlang:: html+django
  178. Translations in :ref:`Django templates <topics-templates>` uses two template
  179. tags and a slightly different syntax than in Python code. To give your template
  180. access to these tags, put ``{% load i18n %}`` toward the top of your template.
  181. The ``{% trans %}`` template tag translates either a constant string
  182. (enclosed in single or double quotes) or variable content::
  183. <title>{% trans "This is the title." %}</title>
  184. <title>{% trans myvar %}</title>
  185. If the ``noop`` option is present, variable lookup still takes place but the
  186. translation is skipped. This is useful when "stubbing out" content that will
  187. require translation in the future::
  188. <title>{% trans "myvar" noop %}</title>
  189. It's not possible to mix a template variable inside a string within ``{% trans
  190. %}``. If your translations require strings with variables (placeholders), use
  191. ``{% blocktrans %}``::
  192. {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
  193. To translate a template expression -- say, using template filters -- you need
  194. to bind the expression to a local variable for use within the translation
  195. block::
  196. {% blocktrans with value|filter as myvar %}
  197. This will have {{ myvar }} inside.
  198. {% endblocktrans %}
  199. If you need to bind more than one expression inside a ``blocktrans`` tag,
  200. separate the pieces with ``and``::
  201. {% blocktrans with book|title as book_t and author|title as author_t %}
  202. This is {{ book_t }} by {{ author_t }}
  203. {% endblocktrans %}
  204. To pluralize, specify both the singular and plural forms with the
  205. ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
  206. ``{% endblocktrans %}``. Example::
  207. {% blocktrans count list|length as counter %}
  208. There is only one {{ name }} object.
  209. {% plural %}
  210. There are {{ counter }} {{ name }} objects.
  211. {% endblocktrans %}
  212. Internally, all block and inline translations use the appropriate
  213. ``ugettext`` / ``ungettext`` call.
  214. Each ``RequestContext`` has access to three translation-specific variables:
  215. * ``LANGUAGES`` is a list of tuples in which the first element is the
  216. language code and the second is the language name (translated into the
  217. currently active locale).
  218. * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
  219. Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`,
  220. below.)
  221. * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
  222. right-to-left language, e.g.: Hebrew, Arabic. If False it's a
  223. left-to-right language, e.g.: English, French, German etc.
  224. If you don't use the ``RequestContext`` extension, you can get those values with
  225. three tags::
  226. {% get_current_language as LANGUAGE_CODE %}
  227. {% get_available_languages as LANGUAGES %}
  228. {% get_current_language_bidi as LANGUAGE_BIDI %}
  229. These tags also require a ``{% load i18n %}``.
  230. Translation hooks are also available within any template block tag that accepts
  231. constant strings. In those cases, just use ``_()`` syntax to specify a
  232. translation string::
  233. {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
  234. In this case, both the tag and the filter will see the already-translated
  235. string, so they don't need to be aware of translations.
  236. .. note::
  237. In this example, the translation infrastructure will be passed the string
  238. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  239. translated string will need to contain the comma so that the filter
  240. parsing code knows how to split up the arguments. For example, a German
  241. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  242. (keeping the comma intact).
  243. .. _Django templates: ../templates_python/
  244. Working with lazy translation objects
  245. -------------------------------------
  246. .. highlightlang:: python
  247. Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
  248. and utility functions is a common operation. When you're working with these
  249. objects elsewhere in your code, you should ensure that you don't accidentally
  250. convert them to strings, because they should be converted as late as possible
  251. (so that the correct locale is in effect). This necessitates the use of a
  252. couple of helper functions.
  253. Joining strings: string_concat()
  254. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  255. Standard Python string joins (``''.join([...])``) will not work on lists
  256. containing lazy translation objects. Instead, you can use
  257. ``django.utils.translation.string_concat()``, which creates a lazy object that
  258. concatenates its contents *and* converts them to strings only when the result
  259. is included in a string. For example::
  260. from django.utils.translation import string_concat
  261. ...
  262. name = ugettext_lazy(u'John Lennon')
  263. instrument = ugettext_lazy(u'guitar')
  264. result = string_concat([name, ': ', instrument])
  265. In this case, the lazy translations in ``result`` will only be converted to
  266. strings when ``result`` itself is used in a string (usually at template
  267. rendering time).
  268. The allow_lazy() decorator
  269. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  270. Django offers many utility functions (particularly in ``django.utils``) that
  271. take a string as their first argument and do something to that string. These
  272. functions are used by template filters as well as directly in other code.
  273. If you write your own similar functions and deal with translations, you'll
  274. face the problem of what to do when the first argument is a lazy translation
  275. object. You don't want to convert it to a string immediately, because you might
  276. be using this function outside of a view (and hence the current thread's locale
  277. setting will not be correct).
  278. For cases like this, use the ``django.utils.functional.allow_lazy()``
  279. decorator. It modifies the function so that *if* it's called with a lazy
  280. translation as the first argument, the function evaluation is delayed until it
  281. needs to be converted to a string.
  282. For example::
  283. from django.utils.functional import allow_lazy
  284. def fancy_utility_function(s, ...):
  285. # Do some conversion on string 's'
  286. ...
  287. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  288. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  289. a number of extra arguments (``*args``) specifying the type(s) that the
  290. original function can return. Usually, it's enough to include ``unicode`` here
  291. and ensure that your function returns only Unicode strings.
  292. Using this decorator means you can write your function and assume that the
  293. input is a proper string, then add support for lazy translation objects at the
  294. end.
  295. .. _how-to-create-language-files:
  296. 2. How to create language files
  297. ===============================
  298. Once you've tagged your strings for later translation, you need to write (or
  299. obtain) the language translations themselves. Here's how that works.
  300. .. admonition:: Locale restrictions
  301. Django does not support localizing your application into a locale for
  302. which Django itself has not been translated. In this case, it will ignore
  303. your translation files. If you were to try this and Django supported it,
  304. you would inevitably see a mixture of translated strings (from your
  305. application) and English strings (from Django itself). If you want to
  306. support a locale for your application that is not already part of
  307. Django, you'll need to make at least a minimal translation of the Django
  308. core. See the relevant :ref:`LocaleMiddleware note<locale-middleware-notes>`
  309. for more details.
  310. Message files
  311. -------------
  312. The first step is to create a **message file** for a new language. A message
  313. file is a plain-text file, representing a single language, that contains all
  314. available translation strings and how they should be represented in the given
  315. language. Message files have a ``.po`` file extension.
  316. Django comes with a tool, ``django-admin.py makemessages``, that automates the
  317. creation and upkeep of these files.
  318. .. admonition:: A note to Django veterans
  319. The old tool ``bin/make-messages.py`` has been moved to the command
  320. ``django-admin.py makemessages`` to provide consistency throughout Django.
  321. To create or update a message file, run this command::
  322. django-admin.py makemessages -l de
  323. ...where ``de`` is the language code for the message file you want to create.
  324. The language code, in this case, is in locale format. For example, it's
  325. ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian German.
  326. The script should be run from one of three places:
  327. * The root directory of your Django project.
  328. * The root directory of your Django app.
  329. * The root ``django`` directory (not a Subversion checkout, but the one
  330. that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
  331. path). This is only relevant when you are creating a translation for
  332. Django itself, see :ref:`contributing-translations`.
  333. Th script runs over your project source tree or your application source tree and
  334. pulls out all strings marked for translation. It creates (or updates) a message
  335. file in the directory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the
  336. file will be ``locale/de/LC_MESSAGES/django.po``.
  337. By default ``django-admin.py makemessages`` examines every file that has the
  338. ``.html`` file extension. In case you want to override that default, use the
  339. ``--extension`` or ``-e`` option to specify the file extensions to examine::
  340. django-admin.py makemessages -l de -e txt
  341. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
  342. multiple times::
  343. django-admin.py makemessages -l=de -e=html,txt -e xml
  344. When `creating JavaScript translation catalogs`_ you need to use the special
  345. 'djangojs' domain, **not** ``-e js``.
  346. .. _create a JavaScript translation catalog: `Creating JavaScript translation catalogs`_
  347. .. admonition:: No gettext?
  348. If you don't have the ``gettext`` utilities installed, ``django-admin.py
  349. makemessages`` will create empty files. If that's the case, either install
  350. the ``gettext`` utilities or just copy the English message file
  351. (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
  352. point; it's just an empty translation file.
  353. .. admonition:: Working on Windows?
  354. If you're using Windows and need to install the GNU gettext utilities so
  355. ``django-admin makemessages`` works see `gettext on Windows`_ for more
  356. information.
  357. The format of ``.po`` files is straightforward. Each ``.po`` file contains a
  358. small bit of metadata, such as the translation maintainer's contact
  359. information, but the bulk of the file is a list of **messages** -- simple
  360. mappings between translation strings and the actual translated text for the
  361. particular language.
  362. For example, if your Django app contained a translation string for the text
  363. ``"Welcome to my site."``, like so::
  364. _("Welcome to my site.")
  365. ...then ``django-admin.py makemessages`` will have created a ``.po`` file
  366. containing the following snippet -- a message::
  367. #: path/to/python/module.py:23
  368. msgid "Welcome to my site."
  369. msgstr ""
  370. A quick explanation:
  371. * ``msgid`` is the translation string, which appears in the source. Don't
  372. change it.
  373. * ``msgstr`` is where you put the language-specific translation. It starts
  374. out empty, so it's your responsibility to change it. Make sure you keep
  375. the quotes around your translation.
  376. * As a convenience, each message includes, in the form of a comment line
  377. prefixed with ``#`` and located above the ``msgid`` line, the filename and
  378. line number from which the translation string was gleaned.
  379. Long messages are a special case. There, the first string directly after the
  380. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
  381. written over the next few lines as one string per line. Those strings are
  382. directly concatenated. Don't forget trailing spaces within the strings;
  383. otherwise, they'll be tacked together without whitespace!
  384. .. admonition:: Mind your charset
  385. When creating a PO file with your favorite text editor, first edit
  386. the charset line (search for ``"CHARSET"``) and set it to the charset
  387. you'll be using to edit the content. Due to the way the ``gettext`` tools
  388. work internally and because we want to allow non-ASCII source strings in
  389. Django's core and your applications, you **must** use UTF-8 as the encoding
  390. for your PO file. This means that everybody will be using the same
  391. encoding, which is important when Django processes the PO files.
  392. To reexamine all source code and templates for new translation strings and
  393. update all message files for **all** languages, run this::
  394. django-admin.py makemessages -a
  395. Compiling message files
  396. -----------------------
  397. After you create your message file -- and each time you make changes to it --
  398. you'll need to compile it into a more efficient form, for use by ``gettext``.
  399. Do this with the ``django-admin.py compilemessages`` utility.
  400. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
  401. are binary files optimized for use by ``gettext``. In the same directory from
  402. which you ran ``django-admin.py makemessages``, run ``django-admin.py
  403. compilemessages`` like this::
  404. django-admin.py compilemessages
  405. That's it. Your translations are ready for use.
  406. .. admonition:: A note to Django veterans
  407. The old tool ``bin/compile-messages.py`` has been moved to the command
  408. ``django-admin.py compilemessages`` to provide consistency throughout
  409. Django.
  410. .. admonition:: Working on Windows?
  411. If you're using Windows and need to install the GNU gettext utilities so
  412. ``django-admin compilemessages`` works see `gettext on Windows`_ for more
  413. information.
  414. .. _how-django-discovers-language-preference:
  415. 3. How Django discovers language preference
  416. ===========================================
  417. Once you've prepared your translations -- or, if you just want to use the
  418. translations that come with Django -- you'll just need to activate translation
  419. for your app.
  420. Behind the scenes, Django has a very flexible model of deciding which language
  421. should be used -- installation-wide, for a particular user, or both.
  422. To set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.
  423. Django uses this language as the default translation -- the final attempt if no
  424. other translator finds a translation.
  425. If all you want to do is run Django with your native language, and a language
  426. file is available for your language, all you need to do is set
  427. ``LANGUAGE_CODE``.
  428. If you want to let each individual user specify which language he or she
  429. prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
  430. selection based on data from the request. It customizes content for each user.
  431. To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
  432. to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
  433. should follow these guidelines:
  434. * Make sure it's one of the first middlewares installed.
  435. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
  436. makes use of session data.
  437. * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
  438. For example, your ``MIDDLEWARE_CLASSES`` might look like this::
  439. MIDDLEWARE_CLASSES = (
  440. 'django.contrib.sessions.middleware.SessionMiddleware',
  441. 'django.middleware.locale.LocaleMiddleware',
  442. 'django.middleware.common.CommonMiddleware',
  443. )
  444. (For more on middleware, see the :ref:`middleware documentation
  445. <topics-http-middleware>`.)
  446. ``LocaleMiddleware`` tries to determine the user's language preference by
  447. following this algorithm:
  448. * First, it looks for a ``django_language`` key in the current user's
  449. session.
  450. * Failing that, it looks for a cookie.
  451. .. versionchanged:: 1.0
  452. In Django version 0.96 and before, the cookie's name is hard-coded to
  453. ``django_language``. In Django 1,0, The cookie name is set by the
  454. ``LANGUAGE_COOKIE_NAME`` setting. (The default name is
  455. ``django_language``.)
  456. * Failing that, it looks at the ``Accept-Language`` HTTP header. This
  457. header is sent by your browser and tells the server which language(s) you
  458. prefer, in order by priority. Django tries each language in the header
  459. until it finds one with available translations.
  460. * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
  461. .. _locale-middleware-notes:
  462. Notes:
  463. * In each of these places, the language preference is expected to be in the
  464. standard language format, as a string. For example, Brazilian Portuguese
  465. is ``pt-br``.
  466. * If a base language is available but the sublanguage specified is not,
  467. Django uses the base language. For example, if a user specifies ``de-at``
  468. (Austrian German) but Django only has ``de`` available, Django uses
  469. ``de``.
  470. * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
  471. If you want to restrict the language selection to a subset of provided
  472. languages (because your application doesn't provide all those languages),
  473. set ``LANGUAGES`` to a list of languages. For example::
  474. LANGUAGES = (
  475. ('de', _('German')),
  476. ('en', _('English')),
  477. )
  478. This example restricts languages that are available for automatic
  479. selection to German and English (and any sublanguage, like de-ch or
  480. en-us).
  481. .. _LANGUAGES setting: ../settings/#languages
  482. * If you define a custom ``LANGUAGES`` setting, as explained in the
  483. previous bullet, it's OK to mark the languages as translation strings
  484. -- but use a "dummy" ``ugettext()`` function, not the one in
  485. ``django.utils.translation``. You should *never* import
  486. ``django.utils.translation`` from within your settings file, because that
  487. module in itself depends on the settings, and that would cause a circular
  488. import.
  489. The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
  490. settings file::
  491. ugettext = lambda s: s
  492. LANGUAGES = (
  493. ('de', ugettext('German')),
  494. ('en', ugettext('English')),
  495. )
  496. With this arrangement, ``django-admin.py makemessages`` will still find
  497. and mark these strings for translation, but the translation won't happen
  498. at runtime -- so you'll have to remember to wrap the languages in the
  499. *real* ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
  500. * The ``LocaleMiddleware`` can only select languages for which there is a
  501. Django-provided base translation. If you want to provide translations
  502. for your application that aren't already in the set of translations
  503. in Django's source tree, you'll want to provide at least basic
  504. translations for that language. For example, Django uses technical
  505. message IDs to translate date formats and time formats -- so you will
  506. need at least those translations for the system to work correctly.
  507. A good starting point is to copy the English ``.po`` file and to
  508. translate at least the technical messages -- maybe the validation
  509. messages, too.
  510. Technical message IDs are easily recognized; they're all upper case. You
  511. don't translate the message ID as with other messages, you provide the
  512. correct local variant on the provided English value. For example, with
  513. ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
  514. be the format string that you want to use in your language. The format
  515. is identical to the format strings used by the ``now`` template tag.
  516. Once ``LocaleMiddleware`` determines the user's preference, it makes this
  517. preference available as ``request.LANGUAGE_CODE`` for each
  518. :class:`~django.http.HttpRequest`. Feel free to read this value in your view
  519. code. Here's a simple example::
  520. def hello_world(request, count):
  521. if request.LANGUAGE_CODE == 'de-at':
  522. return HttpResponse("You prefer to read Austrian German.")
  523. else:
  524. return HttpResponse("You prefer to read another language.")
  525. Note that, with static (middleware-less) translation, the language is in
  526. ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
  527. in ``request.LANGUAGE_CODE``.
  528. .. _settings file: ../settings/
  529. .. _middleware documentation: ../middleware/
  530. .. _session: ../sessions/
  531. .. _request object: ../request_response/#httprequest-objects
  532. .. _translations-in-your-own-projects:
  533. Using translations in your own projects
  534. =======================================
  535. Django looks for translations by following this algorithm:
  536. * First, it looks for a ``locale`` directory in the application directory
  537. of the view that's being called. If it finds a translation for the
  538. selected language, the translation will be installed.
  539. * Next, it looks for a ``locale`` directory in the project directory. If it
  540. finds a translation, the translation will be installed.
  541. * Finally, it checks the Django-provided base translation in
  542. ``django/conf/locale``.
  543. This way, you can write applications that include their own translations, and
  544. you can override base translations in your project path. Or, you can just build
  545. a big project out of several apps and put all translations into one big project
  546. message file. The choice is yours.
  547. .. note::
  548. If you're using manually configured settings, as described
  549. :ref:`settings-without-django-settings-module`, the ``locale`` directory in
  550. the project directory will not be examined, since Django loses the ability
  551. to work out the location of the project directory. (Django normally uses the
  552. location of the settings file to determine this, and a settings file doesn't
  553. exist if you're manually configuring your settings.)
  554. All message file repositories are structured the same way. They are:
  555. * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  556. * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  557. * All paths listed in ``LOCALE_PATHS`` in your settings file are
  558. searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
  559. * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
  560. To create message files, you use the same ``django-admin.py makemessages``
  561. tool as with the Django message files. You only need to be in the right place
  562. -- in the directory where either the ``conf/locale`` (in case of the source
  563. tree) or the ``locale/`` (in case of app messages or project messages)
  564. directory are located. And you use the same ``django-admin.py compilemessages``
  565. to produce the binary ``django.mo`` files that are used by ``gettext``.
  566. You can also run ``django-admin.py compilemessages --settings=path.to.settings``
  567. to make the compiler process all the directories in your ``LOCALE_PATHS``
  568. setting.
  569. Application message files are a bit complicated to discover -- they need the
  570. ``LocaleMiddleware``. If you don't use the middleware, only the Django message
  571. files and project message files will be processed.
  572. Finally, you should give some thought to the structure of your translation
  573. files. If your applications need to be delivered to other users and will
  574. be used in other projects, you might want to use app-specific translations.
  575. But using app-specific translations and project translations could produce
  576. weird problems with ``makemessages``: ``makemessages`` will traverse all
  577. directories below the current path and so might put message IDs into the
  578. project message file that are already in application message files.
  579. The easiest way out is to store applications that are not part of the project
  580. (and so carry their own translations) outside the project tree. That way,
  581. ``django-admin.py makemessages`` on the project level will only translate
  582. strings that are connected to your explicit project and not strings that are
  583. distributed independently.
  584. The ``set_language`` redirect view
  585. ==================================
  586. As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
  587. that sets a user's language preference and redirects back to the previous page.
  588. Activate this view by adding the following line to your URLconf::
  589. (r'^i18n/', include('django.conf.urls.i18n')),
  590. (Note that this example makes the view available at ``/i18n/setlang/``.)
  591. The view expects to be called via the ``POST`` method, with a ``language``
  592. parameter set in request. If session support is enabled, the view
  593. saves the language choice in the user's session. Otherwise, it saves the
  594. language choice in a cookie that is by default named ``django_language``.
  595. (The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting.)
  596. After setting the language choice, Django redirects the user, following this
  597. algorithm:
  598. * Django looks for a ``next`` parameter in the ``POST`` data.
  599. * If that doesn't exist, or is empty, Django tries the URL in the
  600. ``Referrer`` header.
  601. * If that's empty -- say, if a user's browser suppresses that header --
  602. then the user will be redirected to ``/`` (the site root) as a fallback.
  603. Here's example HTML template code:
  604. .. code-block:: html+django
  605. <form action="/i18n/setlang/" method="post">
  606. <input name="next" type="hidden" value="/next/page/" />
  607. <select name="language">
  608. {% for lang in LANGUAGES %}
  609. <option value="{{ lang.0 }}">{{ lang.1 }}</option>
  610. {% endfor %}
  611. </select>
  612. <input type="submit" value="Go" />
  613. </form>
  614. Translations and JavaScript
  615. ===========================
  616. Adding translations to JavaScript poses some problems:
  617. * JavaScript code doesn't have access to a ``gettext`` implementation.
  618. * JavaScript code doesn't have access to .po or .mo files; they need to be
  619. delivered by the server.
  620. * The translation catalogs for JavaScript should be kept as small as
  621. possible.
  622. Django provides an integrated solution for these problems: It passes the
  623. translations into JavaScript, so you can call ``gettext``, etc., from within
  624. JavaScript.
  625. The ``javascript_catalog`` view
  626. -------------------------------
  627. The main solution to these problems is the ``javascript_catalog`` view, which
  628. sends out a JavaScript code library with functions that mimic the ``gettext``
  629. interface, plus an array of translation strings. Those translation strings are
  630. taken from the application, project or Django core, according to what you
  631. specify in either the info_dict or the URL.
  632. You hook it up like this::
  633. js_info_dict = {
  634. 'packages': ('your.app.package',),
  635. }
  636. urlpatterns = patterns('',
  637. (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
  638. )
  639. Each string in ``packages`` should be in Python dotted-package syntax (the
  640. same format as the strings in ``INSTALLED_APPS``) and should refer to a package
  641. that contains a ``locale`` directory. If you specify multiple packages, all
  642. those catalogs are merged into one catalog. This is useful if you have
  643. JavaScript that uses strings from different applications.
  644. You can make the view dynamic by putting the packages into the URL pattern::
  645. urlpatterns = patterns('',
  646. (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
  647. )
  648. With this, you specify the packages as a list of package names delimited by '+'
  649. signs in the URL. This is especially useful if your pages use code from
  650. different apps and this changes often and you don't want to pull in one big
  651. catalog file. As a security measure, these values can only be either
  652. ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
  653. Using the JavaScript translation catalog
  654. ----------------------------------------
  655. To use the catalog, just pull in the dynamically generated script like this::
  656. <script type="text/javascript" src="/path/to/jsi18n/"></script>
  657. This is how the admin fetches the translation catalog from the server. When the
  658. catalog is loaded, your JavaScript code can use the standard ``gettext``
  659. interface to access it::
  660. document.write(gettext('this is to be translated'));
  661. There is also an ``ngettext`` interface::
  662. var object_cnt = 1 // or 0, or 2, or 3, ...
  663. s = ngettext('literal for the singular case',
  664. 'literal for the plural case', object_cnt);
  665. and even a string interpolation function::
  666. function interpolate(fmt, obj, named);
  667. The interpolation syntax is borrowed from Python, so the ``interpolate``
  668. function supports both positional and named interpolation:
  669. * Positional interpolation: ``obj`` contains a JavaScript Array object
  670. whose elements values are then sequentially interpolated in their
  671. corresponding ``fmt`` placeholders in the same order they appear.
  672. For example::
  673. fmts = ngettext('There is %s object. Remaining: %s',
  674. 'There are %s objects. Remaining: %s', 11);
  675. s = interpolate(fmts, [11, 20]);
  676. // s is 'There are 11 objects. Remaining: 20'
  677. * Named interpolation: This mode is selected by passing the optional
  678. boolean ``named`` parameter as true. ``obj`` contains a JavaScript
  679. object or associative array. For example::
  680. d = {
  681. count: 10
  682. total: 50
  683. };
  684. fmts = ngettext('Total: %(total)s, there is %(count)s object',
  685. 'there are %(count)s of a total of %(total)s objects', d.count);
  686. s = interpolate(fmts, d, true);
  687. You shouldn't go over the top with string interpolation, though: this is still
  688. JavaScript, so the code has to make repeated regular-expression substitutions.
  689. This isn't as fast as string interpolation in Python, so keep it to those
  690. cases where you really need it (for example, in conjunction with ``ngettext``
  691. to produce proper pluralizations).
  692. Creating JavaScript translation catalogs
  693. ----------------------------------------
  694. You create and update the translation catalogs the same way as the other
  695. Django translation catalogs -- with the django-admin.py makemessages tool. The
  696. only difference is you need to provide a ``-d djangojs`` parameter, like this::
  697. django-admin.py makemessages -d djangojs -l de
  698. This would create or update the translation catalog for JavaScript for German.
  699. After updating translation catalogs, just run ``django-admin.py compilemessages``
  700. the same way as you do with normal Django translation catalogs.
  701. Specialties of Django translation
  702. ==================================
  703. If you know ``gettext``, you might note these specialties in the way Django
  704. does translation:
  705. * The string domain is ``django`` or ``djangojs``. This string domain is
  706. used to differentiate between different programs that store their data
  707. in a common message-file library (usually ``/usr/share/locale/``). The
  708. ``django`` domain is used for python and template translation strings
  709. and is loaded into the global translation catalogs. The ``djangojs``
  710. domain is only used for JavaScript translation catalogs to make sure
  711. that those are as small as possible.
  712. * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
  713. ``xgettext`` and ``msgfmt``. This is mostly for convenience.
  714. ``gettext`` on Windows
  715. ======================
  716. This is only needed for people who either want to extract message IDs or compile
  717. message files (``.po``). Translation work itself just involves editing existing
  718. files of this type, but if you want to create your own message files, or want to
  719. test or compile a changed message file, you will need the ``gettext`` utilities:
  720. * Download the following zip files from
  721. http://sourceforge.net/projects/gettext
  722. * ``gettext-runtime-X.bin.woe32.zip``
  723. * ``gettext-tools-X.bin.woe32.zip``
  724. * ``libiconv-X.bin.woe32.zip``
  725. * Extract the 3 files in the same folder (i.e. ``C:\Program
  726. Files\gettext-utils``)
  727. * Update the system PATH:
  728. * ``Control Panel > System > Advanced > Environment Variables``
  729. * In the ``System variables`` list, click ``Path``, click ``Edit``
  730. * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
  731. ``Variable value`` field
  732. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
  733. the ``xgettext --version`` command works properly. Some version 0.14.4 binaries
  734. have been found to not support this command. Do not attempt to use Django
  735. translation utilities with a ``gettext`` package if the command ``xgettext
  736. --version`` entered at a Windows command prompt causes a popup window saying
  737. "xgettext.exe has generated errors and will be closed by Windows".