i18n.txt 37 KB

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