translation.txt 59 KB

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