i18n.txt 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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.
  166. ``ungettext`` takes three arguments: the singular translation string, the plural
  167. translation string and the number of objects.
  168. This function is useful when your need you Django application to be localizable
  169. to languages where the number and complexity of `plural forms
  170. <http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
  171. greater than the two forms used in English ('object' for the singular and
  172. 'objects' for all the cases where ``count`` is different from zero, irrespective
  173. of its value.)
  174. For example::
  175. from django.utils.translation import ungettext
  176. def hello_world(request, count):
  177. page = ungettext('there is %(count)d object', 'there are %(count)d objects', count) % {
  178. 'count': count,
  179. }
  180. return HttpResponse(page)
  181. In this example the number of objects is passed to the translation languages as
  182. the ``count`` variable.
  183. Lets see a slightly more complex usage example::
  184. from django.utils.translation import ungettext
  185. count = Report.objects.count()
  186. if count == 1:
  187. name = Report._meta.verbose_name
  188. else:
  189. name = Report._meta.verbose_name_plural
  190. text = ungettext(
  191. 'There is %(count)d %(name)s available.',
  192. 'There are %(count)d %(name)s available.',
  193. count
  194. ) % {
  195. 'count': count,
  196. 'name': name
  197. }
  198. Here we reuse localizable, hopefully already translated literals (contained in
  199. the ``verbose_name`` and ``verbose_name_plural`` model ``Meta`` options) for
  200. other parts of the sentence so all of it is consistently based on the
  201. cardinality of the elements at play.
  202. .. _pluralization-var-notes:
  203. .. note::
  204. When using this technique, make sure you use a single name for every
  205. extrapolated variable included in the literal. In the example above note how
  206. we used the ``name`` Python variable in both translation strings. This
  207. example would fail::
  208. from django.utils.translation import ungettext
  209. from myapp.models import Report
  210. count = Report.objects.count()
  211. d = {
  212. 'count': count,
  213. 'name': Report._meta.verbose_name
  214. 'plural_name': Report._meta.verbose_name_plural
  215. }
  216. text = ungettext(
  217. 'There is %(count)d %(name)s available.',
  218. 'There are %(count)d %(plural_name)s available.',
  219. count
  220. ) % d
  221. You would get a ``a format specification for argument 'name', as in
  222. 'msgstr[0]', doesn't exist in 'msgid'`` error when running
  223. ``django-admin.py compilemessages`` or a ``KeyError`` Python exception at
  224. runtime.
  225. In template code
  226. ----------------
  227. .. highlightlang:: html+django
  228. Translations in :ref:`Django templates <topics-templates>` uses two template
  229. tags and a slightly different syntax than in Python code. To give your template
  230. access to these tags, put ``{% load i18n %}`` toward the top of your template.
  231. The ``{% trans %}`` template tag translates either a constant string
  232. (enclosed in single or double quotes) or variable content::
  233. <title>{% trans "This is the title." %}</title>
  234. <title>{% trans myvar %}</title>
  235. If the ``noop`` option is present, variable lookup still takes place, but the
  236. original text will be returned unchanged. This is useful when "stubbing out"
  237. content that will require translation in the future::
  238. <title>{% trans "myvar" noop %}</title>
  239. Internally, inline translations use an ``ugettext`` call.
  240. It's not possible to mix a template variable inside a string within ``{% trans
  241. %}``. If your translations require strings with variables (placeholders), use
  242. ``{% blocktrans %}``::
  243. {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
  244. To translate a template expression -- say, using template filters -- you need
  245. to bind the expression to a local variable for use within the translation
  246. block::
  247. {% blocktrans with value|filter as myvar %}
  248. This will have {{ myvar }} inside.
  249. {% endblocktrans %}
  250. If you need to bind more than one expression inside a ``blocktrans`` tag,
  251. separate the pieces with ``and``::
  252. {% blocktrans with book|title as book_t and author|title as author_t %}
  253. This is {{ book_t }} by {{ author_t }}
  254. {% endblocktrans %}
  255. To pluralize, specify both the singular and plural forms with the
  256. ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
  257. ``{% endblocktrans %}``. Example::
  258. {% blocktrans count list|length as counter %}
  259. There is only one {{ name }} object.
  260. {% plural %}
  261. There are {{ counter }} {{ name }} objects.
  262. {% endblocktrans %}
  263. When you use the pluralization feature and bind additional values to local
  264. variables apart from the counter value that selects the translated literal to be
  265. used, have in mind that the ``blocktrans`` construct is internally converted
  266. to an ``ungettext`` call. This means the same :ref:`notes regarding ungettext
  267. variables <pluralization-var-notes>` apply.
  268. Each ``RequestContext`` has access to three translation-specific variables:
  269. * ``LANGUAGES`` is a list of tuples in which the first element is the
  270. language code and the second is the language name (translated into the
  271. currently active locale).
  272. * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
  273. Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`,
  274. below.)
  275. * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
  276. right-to-left language, e.g.: Hebrew, Arabic. If False it's a
  277. left-to-right language, e.g.: English, French, German etc.
  278. If you don't use the ``RequestContext`` extension, you can get those values with
  279. three tags::
  280. {% get_current_language as LANGUAGE_CODE %}
  281. {% get_available_languages as LANGUAGES %}
  282. {% get_current_language_bidi as LANGUAGE_BIDI %}
  283. These tags also require a ``{% load i18n %}``.
  284. Translation hooks are also available within any template block tag that accepts
  285. constant strings. In those cases, just use ``_()`` syntax to specify a
  286. translation string::
  287. {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
  288. In this case, both the tag and the filter will see the already-translated
  289. string, so they don't need to be aware of translations.
  290. .. note::
  291. In this example, the translation infrastructure will be passed the string
  292. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  293. translated string will need to contain the comma so that the filter
  294. parsing code knows how to split up the arguments. For example, a German
  295. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  296. (keeping the comma intact).
  297. .. _Django templates: ../templates_python/
  298. Working with lazy translation objects
  299. -------------------------------------
  300. .. highlightlang:: python
  301. Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
  302. and utility functions is a common operation. When you're working with these
  303. objects elsewhere in your code, you should ensure that you don't accidentally
  304. convert them to strings, because they should be converted as late as possible
  305. (so that the correct locale is in effect). This necessitates the use of a
  306. couple of helper functions.
  307. Joining strings: string_concat()
  308. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  309. Standard Python string joins (``''.join([...])``) will not work on lists
  310. containing lazy translation objects. Instead, you can use
  311. ``django.utils.translation.string_concat()``, which creates a lazy object that
  312. concatenates its contents *and* converts them to strings only when the result
  313. is included in a string. For example::
  314. from django.utils.translation import string_concat
  315. ...
  316. name = ugettext_lazy(u'John Lennon')
  317. instrument = ugettext_lazy(u'guitar')
  318. result = string_concat([name, ': ', instrument])
  319. In this case, the lazy translations in ``result`` will only be converted to
  320. strings when ``result`` itself is used in a string (usually at template
  321. rendering time).
  322. The allow_lazy() decorator
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. Django offers many utility functions (particularly in ``django.utils``) that
  325. take a string as their first argument and do something to that string. These
  326. functions are used by template filters as well as directly in other code.
  327. If you write your own similar functions and deal with translations, you'll
  328. face the problem of what to do when the first argument is a lazy translation
  329. object. You don't want to convert it to a string immediately, because you might
  330. be using this function outside of a view (and hence the current thread's locale
  331. setting will not be correct).
  332. For cases like this, use the ``django.utils.functional.allow_lazy()``
  333. decorator. It modifies the function so that *if* it's called with a lazy
  334. translation as the first argument, the function evaluation is delayed until it
  335. needs to be converted to a string.
  336. For example::
  337. from django.utils.functional import allow_lazy
  338. def fancy_utility_function(s, ...):
  339. # Do some conversion on string 's'
  340. ...
  341. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  342. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  343. a number of extra arguments (``*args``) specifying the type(s) that the
  344. original function can return. Usually, it's enough to include ``unicode`` here
  345. and ensure that your function returns only Unicode strings.
  346. Using this decorator means you can write your function and assume that the
  347. input is a proper string, then add support for lazy translation objects at the
  348. end.
  349. .. _how-to-create-language-files:
  350. 2. How to create language files
  351. ===============================
  352. Once you've tagged your strings for later translation, you need to write (or
  353. obtain) the language translations themselves. Here's how that works.
  354. .. admonition:: Locale restrictions
  355. Django does not support localizing your application into a locale for
  356. which Django itself has not been translated. In this case, it will ignore
  357. your translation files. If you were to try this and Django supported it,
  358. you would inevitably see a mixture of translated strings (from your
  359. application) and English strings (from Django itself). If you want to
  360. support a locale for your application that is not already part of
  361. Django, you'll need to make at least a minimal translation of the Django
  362. core. See the relevant :ref:`LocaleMiddleware note<locale-middleware-notes>`
  363. for more details.
  364. Message files
  365. -------------
  366. The first step is to create a **message file** for a new language. A message
  367. file is a plain-text file, representing a single language, that contains all
  368. available translation strings and how they should be represented in the given
  369. language. Message files have a ``.po`` file extension.
  370. Django comes with a tool, ``django-admin.py makemessages``, that automates the
  371. creation and upkeep of these files.
  372. .. admonition:: A note to Django veterans
  373. The old tool ``bin/make-messages.py`` has been moved to the command
  374. ``django-admin.py makemessages`` to provide consistency throughout Django.
  375. To create or update a message file, run this command::
  376. django-admin.py makemessages -l de
  377. ...where ``de`` is the language code for the message file you want to create.
  378. The language code, in this case, is in locale format. For example, it's
  379. ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian German.
  380. The script should be run from one of three places:
  381. * The root directory of your Django project.
  382. * The root directory of your Django app.
  383. * The root ``django`` directory (not a Subversion checkout, but the one
  384. that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
  385. path). This is only relevant when you are creating a translation for
  386. Django itself, see :ref:`contributing-translations`.
  387. The script runs over your project source tree or your application source tree
  388. and pulls out all strings marked for translation. It creates (or updates) a
  389. message file in the directory ``locale/LANG/LC_MESSAGES``. In the ``de``
  390. example, the file will be ``locale/de/LC_MESSAGES/django.po``.
  391. By default ``django-admin.py makemessages`` examines every file that has the
  392. ``.html`` file extension. In case you want to override that default, use the
  393. ``--extension`` or ``-e`` option to specify the file extensions to examine::
  394. django-admin.py makemessages -l de -e txt
  395. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
  396. multiple times::
  397. django-admin.py makemessages -l=de -e=html,txt -e xml
  398. When `creating JavaScript translation catalogs`_ you need to use the special
  399. 'djangojs' domain, **not** ``-e js``.
  400. .. _create a JavaScript translation catalog: `Creating JavaScript translation catalogs`_
  401. .. admonition:: No gettext?
  402. If you don't have the ``gettext`` utilities installed, ``django-admin.py
  403. makemessages`` will create empty files. If that's the case, either install
  404. the ``gettext`` utilities or just copy the English message file
  405. (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
  406. point; it's just an empty translation file.
  407. .. admonition:: Working on Windows?
  408. If you're using Windows and need to install the GNU gettext utilities so
  409. ``django-admin makemessages`` works see `gettext on Windows`_ for more
  410. information.
  411. The format of ``.po`` files is straightforward. Each ``.po`` file contains a
  412. small bit of metadata, such as the translation maintainer's contact
  413. information, but the bulk of the file is a list of **messages** -- simple
  414. mappings between translation strings and the actual translated text for the
  415. particular language.
  416. For example, if your Django app contained a translation string for the text
  417. ``"Welcome to my site."``, like so::
  418. _("Welcome to my site.")
  419. ...then ``django-admin.py makemessages`` will have created a ``.po`` file
  420. containing the following snippet -- a message::
  421. #: path/to/python/module.py:23
  422. msgid "Welcome to my site."
  423. msgstr ""
  424. A quick explanation:
  425. * ``msgid`` is the translation string, which appears in the source. Don't
  426. change it.
  427. * ``msgstr`` is where you put the language-specific translation. It starts
  428. out empty, so it's your responsibility to change it. Make sure you keep
  429. the quotes around your translation.
  430. * As a convenience, each message includes, in the form of a comment line
  431. prefixed with ``#`` and located above the ``msgid`` line, the filename and
  432. line number from which the translation string was gleaned.
  433. Long messages are a special case. There, the first string directly after the
  434. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
  435. written over the next few lines as one string per line. Those strings are
  436. directly concatenated. Don't forget trailing spaces within the strings;
  437. otherwise, they'll be tacked together without whitespace!
  438. .. admonition:: Mind your charset
  439. When creating a PO file with your favorite text editor, first edit
  440. the charset line (search for ``"CHARSET"``) and set it to the charset
  441. you'll be using to edit the content. Due to the way the ``gettext`` tools
  442. work internally and because we want to allow non-ASCII source strings in
  443. Django's core and your applications, you **must** use UTF-8 as the encoding
  444. for your PO file. This means that everybody will be using the same
  445. encoding, which is important when Django processes the PO files.
  446. To reexamine all source code and templates for new translation strings and
  447. update all message files for **all** languages, run this::
  448. django-admin.py makemessages -a
  449. Compiling message files
  450. -----------------------
  451. After you create your message file -- and each time you make changes to it --
  452. you'll need to compile it into a more efficient form, for use by ``gettext``.
  453. Do this with the ``django-admin.py compilemessages`` utility.
  454. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
  455. are binary files optimized for use by ``gettext``. In the same directory from
  456. which you ran ``django-admin.py makemessages``, run ``django-admin.py
  457. compilemessages`` like this::
  458. django-admin.py compilemessages
  459. That's it. Your translations are ready for use.
  460. .. admonition:: A note to Django veterans
  461. The old tool ``bin/compile-messages.py`` has been moved to the command
  462. ``django-admin.py compilemessages`` to provide consistency throughout
  463. Django.
  464. .. admonition:: Working on Windows?
  465. If you're using Windows and need to install the GNU gettext utilities so
  466. ``django-admin compilemessages`` works see `gettext on Windows`_ for more
  467. information.
  468. .. _how-django-discovers-language-preference:
  469. 3. How Django discovers language preference
  470. ===========================================
  471. Once you've prepared your translations -- or, if you just want to use the
  472. translations that come with Django -- you'll just need to activate translation
  473. for your app.
  474. Behind the scenes, Django has a very flexible model of deciding which language
  475. should be used -- installation-wide, for a particular user, or both.
  476. To set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.
  477. Django uses this language as the default translation -- the final attempt if no
  478. other translator finds a translation.
  479. If all you want to do is run Django with your native language, and a language
  480. file is available for your language, all you need to do is set
  481. ``LANGUAGE_CODE``.
  482. If you want to let each individual user specify which language he or she
  483. prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
  484. selection based on data from the request. It customizes content for each user.
  485. To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
  486. to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
  487. should follow these guidelines:
  488. * Make sure it's one of the first middlewares installed.
  489. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
  490. makes use of session data.
  491. * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
  492. For example, your ``MIDDLEWARE_CLASSES`` might look like this::
  493. MIDDLEWARE_CLASSES = (
  494. 'django.contrib.sessions.middleware.SessionMiddleware',
  495. 'django.middleware.locale.LocaleMiddleware',
  496. 'django.middleware.common.CommonMiddleware',
  497. )
  498. (For more on middleware, see the :ref:`middleware documentation
  499. <topics-http-middleware>`.)
  500. ``LocaleMiddleware`` tries to determine the user's language preference by
  501. following this algorithm:
  502. * First, it looks for a ``django_language`` key in the current user's
  503. session.
  504. * Failing that, it looks for a cookie.
  505. .. versionchanged:: 1.0
  506. In Django version 0.96 and before, the cookie's name is hard-coded to
  507. ``django_language``. In Django 1,0, The cookie name is set by the
  508. ``LANGUAGE_COOKIE_NAME`` setting. (The default name is
  509. ``django_language``.)
  510. * Failing that, it looks at the ``Accept-Language`` HTTP header. This
  511. header is sent by your browser and tells the server which language(s) you
  512. prefer, in order by priority. Django tries each language in the header
  513. until it finds one with available translations.
  514. * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
  515. .. _locale-middleware-notes:
  516. Notes:
  517. * In each of these places, the language preference is expected to be in the
  518. standard language format, as a string. For example, Brazilian Portuguese
  519. is ``pt-br``.
  520. * If a base language is available but the sublanguage specified is not,
  521. Django uses the base language. For example, if a user specifies ``de-at``
  522. (Austrian German) but Django only has ``de`` available, Django uses
  523. ``de``.
  524. * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
  525. If you want to restrict the language selection to a subset of provided
  526. languages (because your application doesn't provide all those languages),
  527. set ``LANGUAGES`` to a list of languages. For example::
  528. LANGUAGES = (
  529. ('de', _('German')),
  530. ('en', _('English')),
  531. )
  532. This example restricts languages that are available for automatic
  533. selection to German and English (and any sublanguage, like de-ch or
  534. en-us).
  535. .. _LANGUAGES setting: ../settings/#languages
  536. * If you define a custom ``LANGUAGES`` setting, as explained in the
  537. previous bullet, it's OK to mark the languages as translation strings
  538. -- but use a "dummy" ``ugettext()`` function, not the one in
  539. ``django.utils.translation``. You should *never* import
  540. ``django.utils.translation`` from within your settings file, because that
  541. module in itself depends on the settings, and that would cause a circular
  542. import.
  543. The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
  544. settings file::
  545. ugettext = lambda s: s
  546. LANGUAGES = (
  547. ('de', ugettext('German')),
  548. ('en', ugettext('English')),
  549. )
  550. With this arrangement, ``django-admin.py makemessages`` will still find
  551. and mark these strings for translation, but the translation won't happen
  552. at runtime -- so you'll have to remember to wrap the languages in the
  553. *real* ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
  554. * The ``LocaleMiddleware`` can only select languages for which there is a
  555. Django-provided base translation. If you want to provide translations
  556. for your application that aren't already in the set of translations
  557. in Django's source tree, you'll want to provide at least basic
  558. translations for that language. For example, Django uses technical
  559. message IDs to translate date formats and time formats -- so you will
  560. need at least those translations for the system to work correctly.
  561. A good starting point is to copy the English ``.po`` file and to
  562. translate at least the technical messages -- maybe the validation
  563. messages, too.
  564. Technical message IDs are easily recognized; they're all upper case. You
  565. don't translate the message ID as with other messages, you provide the
  566. correct local variant on the provided English value. For example, with
  567. ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
  568. be the format string that you want to use in your language. The format
  569. is identical to the format strings used by the ``now`` template tag.
  570. Once ``LocaleMiddleware`` determines the user's preference, it makes this
  571. preference available as ``request.LANGUAGE_CODE`` for each
  572. :class:`~django.http.HttpRequest`. Feel free to read this value in your view
  573. code. Here's a simple example::
  574. def hello_world(request, count):
  575. if request.LANGUAGE_CODE == 'de-at':
  576. return HttpResponse("You prefer to read Austrian German.")
  577. else:
  578. return HttpResponse("You prefer to read another language.")
  579. Note that, with static (middleware-less) translation, the language is in
  580. ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
  581. in ``request.LANGUAGE_CODE``.
  582. .. _settings file: ../settings/
  583. .. _middleware documentation: ../middleware/
  584. .. _session: ../sessions/
  585. .. _request object: ../request_response/#httprequest-objects
  586. .. _translations-in-your-own-projects:
  587. Using translations in your own projects
  588. =======================================
  589. Django looks for translations by following this algorithm:
  590. * First, it looks for a ``locale`` directory in the application directory
  591. of the view that's being called. If it finds a translation for the
  592. selected language, the translation will be installed.
  593. * Next, it looks for a ``locale`` directory in the project directory. If it
  594. finds a translation, the translation will be installed.
  595. * Finally, it checks the Django-provided base translation in
  596. ``django/conf/locale``.
  597. This way, you can write applications that include their own translations, and
  598. you can override base translations in your project path. Or, you can just build
  599. a big project out of several apps and put all translations into one big project
  600. message file. The choice is yours.
  601. .. note::
  602. If you're using manually configured settings, as described
  603. :ref:`settings-without-django-settings-module`, the ``locale`` directory in
  604. the project directory will not be examined, since Django loses the ability
  605. to work out the location of the project directory. (Django normally uses the
  606. location of the settings file to determine this, and a settings file doesn't
  607. exist if you're manually configuring your settings.)
  608. All message file repositories are structured the same way. They are:
  609. * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  610. * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  611. * All paths listed in ``LOCALE_PATHS`` in your settings file are
  612. searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
  613. * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
  614. To create message files, you use the same ``django-admin.py makemessages``
  615. tool as with the Django message files. You only need to be in the right place
  616. -- in the directory where either the ``conf/locale`` (in case of the source
  617. tree) or the ``locale/`` (in case of app messages or project messages)
  618. directory are located. And you use the same ``django-admin.py compilemessages``
  619. to produce the binary ``django.mo`` files that are used by ``gettext``.
  620. You can also run ``django-admin.py compilemessages --settings=path.to.settings``
  621. to make the compiler process all the directories in your ``LOCALE_PATHS``
  622. setting.
  623. Application message files are a bit complicated to discover -- they need the
  624. ``LocaleMiddleware``. If you don't use the middleware, only the Django message
  625. files and project message files will be processed.
  626. Finally, you should give some thought to the structure of your translation
  627. files. If your applications need to be delivered to other users and will
  628. be used in other projects, you might want to use app-specific translations.
  629. But using app-specific translations and project translations could produce
  630. weird problems with ``makemessages``: ``makemessages`` will traverse all
  631. directories below the current path and so might put message IDs into the
  632. project message file that are already in application message files.
  633. The easiest way out is to store applications that are not part of the project
  634. (and so carry their own translations) outside the project tree. That way,
  635. ``django-admin.py makemessages`` on the project level will only translate
  636. strings that are connected to your explicit project and not strings that are
  637. distributed independently.
  638. The ``set_language`` redirect view
  639. ==================================
  640. As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
  641. that sets a user's language preference and redirects back to the previous page.
  642. Activate this view by adding the following line to your URLconf::
  643. (r'^i18n/', include('django.conf.urls.i18n')),
  644. (Note that this example makes the view available at ``/i18n/setlang/``.)
  645. The view expects to be called via the ``POST`` method, with a ``language``
  646. parameter set in request. If session support is enabled, the view
  647. saves the language choice in the user's session. Otherwise, it saves the
  648. language choice in a cookie that is by default named ``django_language``.
  649. (The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting.)
  650. After setting the language choice, Django redirects the user, following this
  651. algorithm:
  652. * Django looks for a ``next`` parameter in the ``POST`` data.
  653. * If that doesn't exist, or is empty, Django tries the URL in the
  654. ``Referrer`` header.
  655. * If that's empty -- say, if a user's browser suppresses that header --
  656. then the user will be redirected to ``/`` (the site root) as a fallback.
  657. Here's example HTML template code:
  658. .. code-block:: html+django
  659. <form action="/i18n/setlang/" method="post">
  660. <input name="next" type="hidden" value="/next/page/" />
  661. <select name="language">
  662. {% for lang in LANGUAGES %}
  663. <option value="{{ lang.0 }}">{{ lang.1 }}</option>
  664. {% endfor %}
  665. </select>
  666. <input type="submit" value="Go" />
  667. </form>
  668. Translations and JavaScript
  669. ===========================
  670. Adding translations to JavaScript poses some problems:
  671. * JavaScript code doesn't have access to a ``gettext`` implementation.
  672. * JavaScript code doesn't have access to .po or .mo files; they need to be
  673. delivered by the server.
  674. * The translation catalogs for JavaScript should be kept as small as
  675. possible.
  676. Django provides an integrated solution for these problems: It passes the
  677. translations into JavaScript, so you can call ``gettext``, etc., from within
  678. JavaScript.
  679. The ``javascript_catalog`` view
  680. -------------------------------
  681. The main solution to these problems is the ``javascript_catalog`` view, which
  682. sends out a JavaScript code library with functions that mimic the ``gettext``
  683. interface, plus an array of translation strings. Those translation strings are
  684. taken from the application, project or Django core, according to what you
  685. specify in either the info_dict or the URL.
  686. You hook it up like this::
  687. js_info_dict = {
  688. 'packages': ('your.app.package',),
  689. }
  690. urlpatterns = patterns('',
  691. (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
  692. )
  693. Each string in ``packages`` should be in Python dotted-package syntax (the
  694. same format as the strings in ``INSTALLED_APPS``) and should refer to a package
  695. that contains a ``locale`` directory. If you specify multiple packages, all
  696. those catalogs are merged into one catalog. This is useful if you have
  697. JavaScript that uses strings from different applications.
  698. You can make the view dynamic by putting the packages into the URL pattern::
  699. urlpatterns = patterns('',
  700. (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
  701. )
  702. With this, you specify the packages as a list of package names delimited by '+'
  703. signs in the URL. This is especially useful if your pages use code from
  704. different apps and this changes often and you don't want to pull in one big
  705. catalog file. As a security measure, these values can only be either
  706. ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
  707. Using the JavaScript translation catalog
  708. ----------------------------------------
  709. To use the catalog, just pull in the dynamically generated script like this::
  710. <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
  711. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
  712. When the catalog is loaded, your JavaScript code can use the standard
  713. ``gettext`` interface to access it::
  714. document.write(gettext('this is to be translated'));
  715. There is also an ``ngettext`` interface::
  716. var object_cnt = 1 // or 0, or 2, or 3, ...
  717. s = ngettext('literal for the singular case',
  718. 'literal for the plural case', object_cnt);
  719. and even a string interpolation function::
  720. function interpolate(fmt, obj, named);
  721. The interpolation syntax is borrowed from Python, so the ``interpolate``
  722. function supports both positional and named interpolation:
  723. * Positional interpolation: ``obj`` contains a JavaScript Array object
  724. whose elements values are then sequentially interpolated in their
  725. corresponding ``fmt`` placeholders in the same order they appear.
  726. For example::
  727. fmts = ngettext('There is %s object. Remaining: %s',
  728. 'There are %s objects. Remaining: %s', 11);
  729. s = interpolate(fmts, [11, 20]);
  730. // s is 'There are 11 objects. Remaining: 20'
  731. * Named interpolation: This mode is selected by passing the optional
  732. boolean ``named`` parameter as true. ``obj`` contains a JavaScript
  733. object or associative array. For example::
  734. d = {
  735. count: 10
  736. total: 50
  737. };
  738. fmts = ngettext('Total: %(total)s, there is %(count)s object',
  739. 'there are %(count)s of a total of %(total)s objects', d.count);
  740. s = interpolate(fmts, d, true);
  741. You shouldn't go over the top with string interpolation, though: this is still
  742. JavaScript, so the code has to make repeated regular-expression substitutions.
  743. This isn't as fast as string interpolation in Python, so keep it to those
  744. cases where you really need it (for example, in conjunction with ``ngettext``
  745. to produce proper pluralizations).
  746. Creating JavaScript translation catalogs
  747. ----------------------------------------
  748. You create and update the translation catalogs the same way as the other
  749. Django translation catalogs -- with the django-admin.py makemessages tool. The
  750. only difference is you need to provide a ``-d djangojs`` parameter, like this::
  751. django-admin.py makemessages -d djangojs -l de
  752. This would create or update the translation catalog for JavaScript for German.
  753. After updating translation catalogs, just run ``django-admin.py compilemessages``
  754. the same way as you do with normal Django translation catalogs.
  755. Specialties of Django translation
  756. ==================================
  757. If you know ``gettext``, you might note these specialties in the way Django
  758. does translation:
  759. * The string domain is ``django`` or ``djangojs``. This string domain is
  760. used to differentiate between different programs that store their data
  761. in a common message-file library (usually ``/usr/share/locale/``). The
  762. ``django`` domain is used for python and template translation strings
  763. and is loaded into the global translation catalogs. The ``djangojs``
  764. domain is only used for JavaScript translation catalogs to make sure
  765. that those are as small as possible.
  766. * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
  767. ``xgettext`` and ``msgfmt``. This is mostly for convenience.
  768. ``gettext`` on Windows
  769. ======================
  770. This is only needed for people who either want to extract message IDs or compile
  771. message files (``.po``). Translation work itself just involves editing existing
  772. files of this type, but if you want to create your own message files, or want to
  773. test or compile a changed message file, you will need the ``gettext`` utilities:
  774. * Download the following zip files from the GNOME servers
  775. http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/ or from one
  776. of its mirrors_
  777. * ``gettext-runtime-X.zip``
  778. * ``gettext-tools-X.zip``
  779. ``X`` is the version number, we recomend using ``0.15`` or higher.
  780. * Extract the contents of the ``bin\`` directories in both files to the
  781. same folder on your system (i.e. ``C:\Program Files\gettext-utils``)
  782. * Update the system PATH:
  783. * ``Control Panel > System > Advanced > Environment Variables``
  784. * In the ``System variables`` list, click ``Path``, click ``Edit``
  785. * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
  786. ``Variable value`` field
  787. .. _mirrors: http://ftp.gnome.org/pub/GNOME/MIRRORS
  788. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
  789. the ``xgettext --version`` command works properly. Some version 0.14.4 binaries
  790. have been found to not support this command. Do not attempt to use Django
  791. translation utilities with a ``gettext`` package if the command ``xgettext
  792. --version`` entered at a Windows command prompt causes a popup window saying
  793. "xgettext.exe has generated errors and will be closed by Windows".