translation.txt 58 KB

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