translation.txt 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  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
  8. number 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. .. note::
  26. There is also an independent but related :setting:`USE_L10N` setting that
  27. controls if Django should implement format localization. See
  28. :doc:`/topics/i18n/formatting` for more details.
  29. .. note::
  30. Make sure you've activated translation for your project (the fastest way is
  31. to check if :setting:`MIDDLEWARE_CLASSES` includes
  32. :mod:`django.middleware.locale.LocaleMiddleware`). If you haven't yet,
  33. see :ref:`how-django-discovers-language-preference`.
  34. Internationalization: in Python code
  35. ====================================
  36. Standard translation
  37. --------------------
  38. Specify a translation string by using the function
  39. :func:`~django.utils.translation.ugettext`. It's convention to import this
  40. as a shorter alias, ``_``, to save typing.
  41. .. note::
  42. Python's standard library ``gettext`` module installs ``_()`` into the
  43. global namespace, as an alias for ``gettext()``. In Django, we have chosen
  44. not to follow this practice, for a couple of reasons:
  45. 1. For international character set (Unicode) support,
  46. :func:`~django.utils.translation.ugettext` is more useful than
  47. ``gettext()``. Sometimes, you should be using
  48. :func:`~django.utils.translation.ugettext_lazy` as the default
  49. translation method for a particular file. Without ``_()`` in the
  50. global namespace, the developer has to think about which is the
  51. most appropriate translation function.
  52. 2. The underscore character (``_``) is used to represent "the previous
  53. result" in Python's interactive shell and doctest tests. Installing a
  54. global ``_()`` function causes interference. Explicitly importing
  55. ``ugettext()`` as ``_()`` avoids this problem.
  56. .. highlightlang:: python
  57. In this example, the text ``"Welcome to my site."`` is marked as a translation
  58. string::
  59. from django.utils.translation import ugettext as _
  60. from django.http import HttpResponse
  61. def my_view(request):
  62. output = _("Welcome to my site.")
  63. return HttpResponse(output)
  64. Obviously, you could code this without using the alias. This example is
  65. identical to the previous one::
  66. from django.utils.translation import ugettext
  67. from django.http import HttpResponse
  68. def my_view(request):
  69. output = ugettext("Welcome to my site.")
  70. return HttpResponse(output)
  71. Translation works on computed values. This example is identical to the previous
  72. two::
  73. def my_view(request):
  74. words = ['Welcome', 'to', 'my', 'site.']
  75. output = _(' '.join(words))
  76. return HttpResponse(output)
  77. Translation works on variables. Again, here's an identical example::
  78. def my_view(request):
  79. sentence = 'Welcome to my site.'
  80. output = _(sentence)
  81. return HttpResponse(output)
  82. (The caveat with using variables or computed values, as in the previous two
  83. examples, is that Django's translation-string-detecting utility,
  84. :djadmin:`django-admin makemessages <makemessages>`, won't be able to find
  85. these strings. More on :djadmin:`makemessages` later.)
  86. The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
  87. specified with Python's standard named-string interpolation syntax. Example::
  88. def my_view(request, m, d):
  89. output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
  90. return HttpResponse(output)
  91. This technique lets language-specific translations reorder the placeholder
  92. text. For example, an English translation may be ``"Today is November 26."``,
  93. while a Spanish translation may be ``"Hoy es 26 de Noviembre."`` -- with the
  94. month and the day placeholders swapped.
  95. For this reason, you should use named-string interpolation (e.g., ``%(day)s``)
  96. instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
  97. have more than a single parameter. If you used positional interpolation,
  98. translations wouldn't be able to reorder placeholder text.
  99. .. _translator-comments:
  100. Comments for translators
  101. ------------------------
  102. If you would like to give translators hints about a translatable string, you
  103. can add a comment prefixed with the ``Translators`` keyword on the line
  104. preceding the string, e.g.::
  105. def my_view(request):
  106. # Translators: This message appears on the home page only
  107. output = ugettext("Welcome to my site.")
  108. The comment will then appear in the resulting ``.po`` file associated with the
  109. translatable construct located below it and should also be displayed by most
  110. translation tools.
  111. .. note:: Just for completeness, this is the corresponding fragment of the
  112. resulting ``.po`` file:
  113. .. code-block:: po
  114. #. Translators: This message appears on the home page only
  115. # path/to/python/file.py:123
  116. msgid "Welcome to my site."
  117. msgstr ""
  118. This also works in templates. See :ref:`translator-comments-in-templates` for
  119. more details.
  120. Marking strings as no-op
  121. ------------------------
  122. Use the function :func:`django.utils.translation.ugettext_noop()` to mark a
  123. string as a translation string without translating it. The string is later
  124. translated from a variable.
  125. Use this if you have constant strings that should be stored in the source
  126. language because they are exchanged over systems or users -- such as strings
  127. in a database -- but should be translated at the last possible point in time,
  128. such as when the string is presented to the user.
  129. Pluralization
  130. -------------
  131. Use the function :func:`django.utils.translation.ungettext()` to specify
  132. pluralized messages.
  133. ``ungettext`` takes three arguments: the singular translation string, the plural
  134. translation string and the number of objects.
  135. This function is useful when you need your Django application to be localizable
  136. to languages where the number and complexity of `plural forms
  137. <http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
  138. greater than the two forms used in English ('object' for the singular and
  139. 'objects' for all the cases where ``count`` is different from one, irrespective
  140. of its value.)
  141. For example::
  142. from django.utils.translation import ungettext
  143. from django.http import HttpResponse
  144. def hello_world(request, count):
  145. page = ungettext(
  146. 'there is %(count)d object',
  147. 'there are %(count)d objects',
  148. count) % {
  149. 'count': count,
  150. }
  151. return HttpResponse(page)
  152. In this example the number of objects is passed to the translation
  153. languages as the ``count`` variable.
  154. Note that pluralization is complicated and works differently in each language.
  155. Comparing ``count`` to 1 isn't always the correct rule. This code looks
  156. sophisticated, but will produce incorrect results for some languages::
  157. from django.utils.translation import ungettext
  158. from myapp.models import Report
  159. count = Report.objects.count()
  160. if count == 1:
  161. name = Report._meta.verbose_name
  162. else:
  163. name = Report._meta.verbose_name_plural
  164. text = ungettext(
  165. 'There is %(count)d %(name)s available.',
  166. 'There are %(count)d %(name)s available.',
  167. count
  168. ) % {
  169. 'count': count,
  170. 'name': name
  171. }
  172. Don't try to implement your own singular-or-plural logic, it won't be correct.
  173. In a case like this, consider something like the following::
  174. text = ungettext(
  175. 'There is %(count)d %(name)s object available.',
  176. 'There are %(count)d %(name)s objects available.',
  177. count
  178. ) % {
  179. 'count': count,
  180. 'name': Report._meta.verbose_name,
  181. }
  182. .. _pluralization-var-notes:
  183. .. note::
  184. When using ``ungettext()``, make sure you use a single name for every
  185. extrapolated variable included in the literal. In the examples above, note
  186. how we used the ``name`` Python variable in both translation strings. This
  187. example, besides being incorrect in some languages as noted above, would
  188. fail::
  189. text = ungettext(
  190. 'There is %(count)d %(name)s available.',
  191. 'There are %(count)d %(plural_name)s available.',
  192. count
  193. ) % {
  194. 'count': Report.objects.count(),
  195. 'name': Report._meta.verbose_name,
  196. 'plural_name': Report._meta.verbose_name_plural
  197. }
  198. You would get an error when running :djadmin:`django-admin
  199. compilemessages <compilemessages>`::
  200. a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'
  201. .. note:: Plural form and po files
  202. Django does not support custom plural equations in po files. As all
  203. translation catalogs are merged, only the plural form for the main Django po
  204. file (in ``django/conf/locale/<lang_code>/LC_MESSAGES/django.po``) is
  205. considered. Plural forms in all other po files are ignored. Therefore, you
  206. should not use different plural equations in your project or application po
  207. files.
  208. .. _contextual-markers:
  209. Contextual markers
  210. ------------------
  211. Sometimes words have several meanings, such as ``"May"`` in English, which
  212. refers to a month name and to a verb. To enable translators to translate
  213. these words correctly in different contexts, you can use the
  214. :func:`django.utils.translation.pgettext()` function, or the
  215. :func:`django.utils.translation.npgettext()` function if the string needs
  216. pluralization. Both take a context string as the first variable.
  217. In the resulting ``.po`` file, the string will then appear as often as there are
  218. different contextual markers for the same string (the context will appear on the
  219. ``msgctxt`` line), allowing the translator to give a different translation for
  220. each of them.
  221. For example::
  222. from django.utils.translation import pgettext
  223. month = pgettext("month name", "May")
  224. or::
  225. from django.db import models
  226. from django.utils.translation import pgettext_lazy
  227. class MyThing(models.Model):
  228. name = models.CharField(help_text=pgettext_lazy(
  229. 'help text for MyThing model', 'This is the help text'))
  230. will appear in the ``.po`` file as:
  231. .. code-block:: po
  232. msgctxt "month name"
  233. msgid "May"
  234. msgstr ""
  235. Contextual markers are also supported by the :ttag:`trans` and
  236. :ttag:`blocktrans` template tags.
  237. .. _lazy-translations:
  238. Lazy translation
  239. ----------------
  240. Use the lazy versions of translation functions in
  241. :mod:`django.utils.translation` (easily recognizable by the ``lazy`` suffix in
  242. their names) to translate strings lazily -- when the value is accessed rather
  243. than when they're called.
  244. These functions store a lazy reference to the string -- not the actual
  245. translation. The translation itself will be done when the string is used in a
  246. string context, such as in template rendering.
  247. This is essential when calls to these functions are located in code paths that
  248. are executed at module load time.
  249. This is something that can easily happen when defining models, forms and
  250. model forms, because Django implements these such that their fields are
  251. actually class-level attributes. For that reason, make sure to use lazy
  252. translations in the following cases:
  253. Model fields and relationships ``verbose_name`` and ``help_text`` option values
  254. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  255. For example, to translate the help text of the *name* field in the following
  256. model, do the following::
  257. from django.db import models
  258. from django.utils.translation import ugettext_lazy as _
  259. class MyThing(models.Model):
  260. name = models.CharField(help_text=_('This is the help text'))
  261. You can mark names of :class:`~django.db.models.ForeignKey`,
  262. :class:`~django.db.models.ManyToManyField` or
  263. :class:`~django.db.models.OneToOneField` relationship as translatable by using
  264. their :attr:`~django.db.models.Options.verbose_name` options::
  265. class MyThing(models.Model):
  266. kind = models.ForeignKey(
  267. ThingKind,
  268. on_delete=models.CASCADE,
  269. related_name='kinds',
  270. verbose_name=_('kind'),
  271. )
  272. Just like you would do in :attr:`~django.db.models.Options.verbose_name` you
  273. should provide a lowercase verbose name text for the relation as Django will
  274. automatically titlecase it when required.
  275. Model verbose names values
  276. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  277. It is recommended to always provide explicit
  278. :attr:`~django.db.models.Options.verbose_name` and
  279. :attr:`~django.db.models.Options.verbose_name_plural` options rather than
  280. relying on the fallback English-centric and somewhat naïve determination of
  281. verbose names Django performs by looking at the model's class name::
  282. from django.db import models
  283. from django.utils.translation import ugettext_lazy as _
  284. class MyThing(models.Model):
  285. name = models.CharField(_('name'), help_text=_('This is the help text'))
  286. class Meta:
  287. verbose_name = _('my thing')
  288. verbose_name_plural = _('my things')
  289. Model methods ``short_description`` attribute values
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  291. For model methods, you can provide translations to Django and the admin site
  292. with the ``short_description`` attribute::
  293. from django.db import models
  294. from django.utils.translation import ugettext_lazy as _
  295. class MyThing(models.Model):
  296. kind = models.ForeignKey(
  297. ThingKind,
  298. on_delete=models.CASCADE,
  299. related_name='kinds',
  300. verbose_name=_('kind'),
  301. )
  302. def is_mouse(self):
  303. return self.kind.type == MOUSE_TYPE
  304. is_mouse.short_description = _('Is it a mouse?')
  305. Working with lazy translation objects
  306. -------------------------------------
  307. The result of a ``ugettext_lazy()`` call can be used wherever you would use a
  308. unicode string (an object with type ``unicode``) in Python. If you try to use
  309. it where a bytestring (a ``str`` object) is expected, things will not work as
  310. expected, since a ``ugettext_lazy()`` object doesn't know how to convert
  311. itself to a bytestring. You can't use a unicode string inside a bytestring,
  312. either, so this is consistent with normal Python behavior. For example::
  313. # This is fine: putting a unicode proxy into a unicode string.
  314. "Hello %s" % ugettext_lazy("people")
  315. # This will not work, since you cannot insert a unicode object
  316. # into a bytestring (nor can you insert our unicode proxy there)
  317. b"Hello %s" % ugettext_lazy("people")
  318. If you ever see output that looks like ``"hello
  319. <django.utils.functional...>"``, you have tried to insert the result of
  320. ``ugettext_lazy()`` into a bytestring. That's a bug in your code.
  321. If you don't like the long ``ugettext_lazy`` name, you can just alias it as
  322. ``_`` (underscore), like so::
  323. from django.db import models
  324. from django.utils.translation import ugettext_lazy as _
  325. class MyThing(models.Model):
  326. name = models.CharField(help_text=_('This is the help text'))
  327. Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
  328. and utility functions is a common operation. When you're working with these
  329. objects elsewhere in your code, you should ensure that you don't accidentally
  330. convert them to strings, because they should be converted as late as possible
  331. (so that the correct locale is in effect). This necessitates the use of the
  332. helper function described next.
  333. .. _lazy-plural-translations:
  334. Lazy translations and plural
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. When using lazy translation for a plural string (``[u]n[p]gettext_lazy``), you
  337. generally don't know the ``number`` argument at the time of the string
  338. definition. Therefore, you are authorized to pass a key name instead of an
  339. integer as the ``number`` argument. Then ``number`` will be looked up in the
  340. dictionary under that key during string interpolation. Here's example::
  341. from django import forms
  342. from django.utils.translation import ungettext_lazy
  343. class MyForm(forms.Form):
  344. error_message = ungettext_lazy("You only provided %(num)d argument",
  345. "You only provided %(num)d arguments", 'num')
  346. def clean(self):
  347. # ...
  348. if error:
  349. raise forms.ValidationError(self.error_message % {'num': number})
  350. If the string contains exactly one unnamed placeholder, you can interpolate
  351. directly with the ``number`` argument::
  352. class MyForm(forms.Form):
  353. error_message = ungettext_lazy("You provided %d argument",
  354. "You provided %d arguments")
  355. def clean(self):
  356. # ...
  357. if error:
  358. raise forms.ValidationError(self.error_message % number)
  359. Joining strings: string_concat()
  360. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  361. Standard Python string joins (``''.join([...])``) will not work on lists
  362. containing lazy translation objects. Instead, you can use
  363. :func:`django.utils.translation.string_concat()`, which creates a lazy object
  364. that concatenates its contents *and* converts them to strings only when the
  365. result is included in a string. For example::
  366. from django.utils.translation import string_concat
  367. from django.utils.translation import ugettext_lazy
  368. ...
  369. name = ugettext_lazy('John Lennon')
  370. instrument = ugettext_lazy('guitar')
  371. result = string_concat(name, ': ', instrument)
  372. In this case, the lazy translations in ``result`` will only be converted to
  373. strings when ``result`` itself is used in a string (usually at template
  374. rendering time).
  375. Other uses of lazy in delayed translations
  376. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  377. For any other case where you would like to delay the translation, but have to
  378. pass the translatable string as argument to another function, you can wrap
  379. this function inside a lazy call yourself. For example::
  380. from django.utils import six # Python 3 compatibility
  381. from django.utils.functional import lazy
  382. from django.utils.safestring import mark_safe
  383. from django.utils.translation import ugettext_lazy as _
  384. mark_safe_lazy = lazy(mark_safe, six.text_type)
  385. And then later::
  386. lazy_string = mark_safe_lazy(_("<p>My <strong>string!</strong></p>"))
  387. Localized names of languages
  388. ----------------------------
  389. .. function:: get_language_info
  390. The ``get_language_info()`` function provides detailed information about
  391. languages::
  392. >>> from django.utils.translation import get_language_info
  393. >>> li = get_language_info('de')
  394. >>> print(li['name'], li['name_local'], li['bidi'])
  395. German Deutsch False
  396. The ``name`` and ``name_local`` attributes of the dictionary contain the name of
  397. the language in English and in the language itself, respectively. The ``bidi``
  398. attribute is True only for bi-directional languages.
  399. The source of the language information is the ``django.conf.locale`` module.
  400. Similar access to this information is available for template code. See below.
  401. .. _specifying-translation-strings-in-template-code:
  402. Internationalization: in template code
  403. ======================================
  404. .. highlightlang:: html+django
  405. Translations in :doc:`Django templates </ref/templates/language>` uses two template
  406. tags and a slightly different syntax than in Python code. To give your template
  407. access to these tags, put ``{% load i18n %}`` toward the top of your template.
  408. As with all template tags, this tag needs to be loaded in all templates which
  409. use translations, even those templates that extend from other templates which
  410. have already loaded the ``i18n`` tag.
  411. .. templatetag:: trans
  412. ``trans`` template tag
  413. ----------------------
  414. The ``{% trans %}`` template tag translates either a constant string
  415. (enclosed in single or double quotes) or variable content::
  416. <title>{% trans "This is the title." %}</title>
  417. <title>{% trans myvar %}</title>
  418. If the ``noop`` option is present, variable lookup still takes place but the
  419. translation is skipped. This is useful when "stubbing out" content that will
  420. require translation in the future::
  421. <title>{% trans "myvar" noop %}</title>
  422. Internally, inline translations use an
  423. :func:`~django.utils.translation.ugettext` call.
  424. In case a template var (``myvar`` above) is passed to the tag, the tag will
  425. first resolve such variable to a string at run-time and then look up that
  426. string in the message catalogs.
  427. It's not possible to mix a template variable inside a string within ``{% trans
  428. %}``. If your translations require strings with variables (placeholders), use
  429. :ttag:`{% blocktrans %}<blocktrans>` instead.
  430. If you'd like to retrieve a translated string without displaying it, you can
  431. use the following syntax::
  432. {% trans "This is the title" as the_title %}
  433. <title>{{ the_title }}</title>
  434. <meta name="description" content="{{ the_title }}">
  435. In practice you'll use this to get a string you can use in multiple places in a
  436. template or so you can use the output as an argument for other template tags or
  437. filters::
  438. {% trans "starting point" as start %}
  439. {% trans "end point" as end %}
  440. {% trans "La Grande Boucle" as race %}
  441. <h1>
  442. <a href="/" title="{% blocktrans %}Back to '{{ race }}' homepage{% endblocktrans %}">{{ race }}</a>
  443. </h1>
  444. <p>
  445. {% for stage in tour_stages %}
  446. {% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br />{% else %}, {% endif %}
  447. {% endfor %}
  448. </p>
  449. ``{% trans %}`` also supports :ref:`contextual markers<contextual-markers>`
  450. using the ``context`` keyword:
  451. .. code-block:: html+django
  452. {% trans "May" context "month name" %}
  453. .. templatetag:: blocktrans
  454. ``blocktrans`` template tag
  455. ---------------------------
  456. Contrarily to the :ttag:`trans` tag, the ``blocktrans`` tag allows you to mark
  457. complex sentences consisting of literals and variable content for translation
  458. by making use of placeholders::
  459. {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
  460. To translate a template expression -- say, accessing object attributes or
  461. using template filters -- you need to bind the expression to a local variable
  462. for use within the translation block. Examples::
  463. {% blocktrans with amount=article.price %}
  464. That will cost $ {{ amount }}.
  465. {% endblocktrans %}
  466. {% blocktrans with myvar=value|filter %}
  467. This will have {{ myvar }} inside.
  468. {% endblocktrans %}
  469. You can use multiple expressions inside a single ``blocktrans`` tag::
  470. {% blocktrans with book_t=book|title author_t=author|title %}
  471. This is {{ book_t }} by {{ author_t }}
  472. {% endblocktrans %}
  473. .. note:: The previous more verbose format is still supported:
  474. ``{% blocktrans with book|title as book_t and author|title as author_t %}``
  475. Other block tags (for example ``{% for %}`` or ``{% if %}``) are not allowed
  476. inside a ``blocktrans`` tag.
  477. If resolving one of the block arguments fails, blocktrans will fall back to
  478. the default language by deactivating the currently active language
  479. temporarily with the :func:`~django.utils.translation.deactivate_all`
  480. function.
  481. This tag also provides for pluralization. To use it:
  482. * Designate and bind a counter value with the name ``count``. This value will
  483. be the one used to select the right plural form.
  484. * Specify both the singular and plural forms separating them with the
  485. ``{% plural %}`` tag within the ``{% blocktrans %}`` and
  486. ``{% endblocktrans %}`` tags.
  487. An example::
  488. {% blocktrans count counter=list|length %}
  489. There is only one {{ name }} object.
  490. {% plural %}
  491. There are {{ counter }} {{ name }} objects.
  492. {% endblocktrans %}
  493. A more complex example::
  494. {% blocktrans with amount=article.price count years=i.length %}
  495. That will cost $ {{ amount }} per year.
  496. {% plural %}
  497. That will cost $ {{ amount }} per {{ years }} years.
  498. {% endblocktrans %}
  499. When you use both the pluralization feature and bind values to local variables
  500. in addition to the counter value, keep in mind that the ``blocktrans``
  501. construct is internally converted to an ``ungettext`` call. This means the
  502. same :ref:`notes regarding ungettext variables <pluralization-var-notes>`
  503. apply.
  504. Reverse URL lookups cannot be carried out within the ``blocktrans`` and should
  505. be retrieved (and stored) beforehand::
  506. {% url 'path.to.view' arg arg2 as the_url %}
  507. {% blocktrans %}
  508. This is a URL: {{ the_url }}
  509. {% endblocktrans %}
  510. If you'd like to retrieve a translated string without displaying it, you can
  511. use the following syntax::
  512. {% blocktrans asvar the_title %}The title is {{ title }}.{% endblocktrans %}
  513. <title>{{ the_title }}</title>
  514. <meta name="description" content="{{ the_title }}">
  515. In practice you'll use this to get a string you can use in multiple places in a
  516. template or so you can use the output as an argument for other template tags or
  517. filters.
  518. .. versionchanged:: 1.9
  519. The ``asvar`` syntax was added.
  520. ``{% blocktrans %}`` also supports :ref:`contextual
  521. markers<contextual-markers>` using the ``context`` keyword:
  522. .. code-block:: html+django
  523. {% blocktrans with name=user.username context "greeting" %}Hi {{ name }}{% endblocktrans %}
  524. Another feature ``{% blocktrans %}`` supports is the ``trimmed`` option. This
  525. option will remove newline characters from the beginning and the end of the
  526. content of the ``{% blocktrans %}`` tag, replace any whitespace at the beginning
  527. and end of a line and merge all lines into one using a space character to
  528. separate them. This is quite useful for indenting the content of a ``{%
  529. blocktrans %}`` tag without having the indentation characters end up in the
  530. corresponding entry in the PO file, which makes the translation process easier.
  531. For instance, the following ``{% blocktrans %}`` tag::
  532. {% blocktrans trimmed %}
  533. First sentence.
  534. Second paragraph.
  535. {% endblocktrans %}
  536. will result in the entry ``"First sentence. Second paragraph."`` in the PO file,
  537. compared to ``"\n First sentence.\n Second sentence.\n"``, if the ``trimmed``
  538. option had not been specified.
  539. String literals passed to tags and filters
  540. ------------------------------------------
  541. You can translate string literals passed as arguments to tags and filters
  542. by using the familiar ``_()`` syntax::
  543. {% some_tag _("Page not found") value|yesno:_("yes,no") %}
  544. In this case, both the tag and the filter will see the translated string,
  545. so they don't need to be aware of translations.
  546. .. note::
  547. In this example, the translation infrastructure will be passed the string
  548. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  549. translated string will need to contain the comma so that the filter
  550. parsing code knows how to split up the arguments. For example, a German
  551. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  552. (keeping the comma intact).
  553. .. _translator-comments-in-templates:
  554. Comments for translators in templates
  555. -------------------------------------
  556. Just like with :ref:`Python code <translator-comments>`, these notes for
  557. translators can be specified using comments, either with the :ttag:`comment`
  558. tag:
  559. .. code-block:: html+django
  560. {% comment %}Translators: View verb{% endcomment %}
  561. {% trans "View" %}
  562. {% comment %}Translators: Short intro blurb{% endcomment %}
  563. <p>{% blocktrans %}A multiline translatable
  564. literal.{% endblocktrans %}</p>
  565. or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:
  566. .. code-block:: html+django
  567. {# Translators: Label of a button that triggers search #}
  568. <button type="submit">{% trans "Go" %}</button>
  569. {# Translators: This is a text of the base template #}
  570. {% blocktrans %}Ambiguous translatable block of text{% endblocktrans %}
  571. .. note:: Just for completeness, these are the corresponding fragments of the
  572. resulting ``.po`` file:
  573. .. code-block:: po
  574. #. Translators: View verb
  575. # path/to/template/file.html:10
  576. msgid "View"
  577. msgstr ""
  578. #. Translators: Short intro blurb
  579. # path/to/template/file.html:13
  580. msgid ""
  581. "A multiline translatable"
  582. "literal."
  583. msgstr ""
  584. # ...
  585. #. Translators: Label of a button that triggers search
  586. # path/to/template/file.html:100
  587. msgid "Go"
  588. msgstr ""
  589. #. Translators: This is a text of the base template
  590. # path/to/template/file.html:103
  591. msgid "Ambiguous translatable block of text"
  592. msgstr ""
  593. .. templatetag:: language
  594. Switching language in templates
  595. -------------------------------
  596. If you want to select a language within a template, you can use the
  597. ``language`` template tag:
  598. .. code-block:: html+django
  599. {% load i18n %}
  600. {% get_current_language as LANGUAGE_CODE %}
  601. <!-- Current language: {{ LANGUAGE_CODE }} -->
  602. <p>{% trans "Welcome to our page" %}</p>
  603. {% language 'en' %}
  604. {% get_current_language as LANGUAGE_CODE %}
  605. <!-- Current language: {{ LANGUAGE_CODE }} -->
  606. <p>{% trans "Welcome to our page" %}</p>
  607. {% endlanguage %}
  608. While the first occurrence of "Welcome to our page" uses the current language,
  609. the second will always be in English.
  610. .. _template-translation-vars:
  611. Other tags
  612. ----------
  613. These tags also require a ``{% load i18n %}``.
  614. .. templatetag:: get_available_languages
  615. ``get_available_languages``
  616. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  617. ``{% get_available_languages as LANGUAGES %}`` returns a list of tuples in
  618. which the first element is the :term:`language code` and the second is the
  619. language name (translated into the currently active locale).
  620. .. templatetag:: get_current_language
  621. ``get_current_language``
  622. ~~~~~~~~~~~~~~~~~~~~~~~~
  623. ``{% get_current_language as LANGUAGE_CODE %}`` returns the current user's
  624. preferred language as a string. Example: ``en-us``. See
  625. :ref:`how-django-discovers-language-preference`.
  626. .. templatetag:: get_current_language_bidi
  627. ``get_current_language_bidi``
  628. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  629. ``{% get_current_language_bidi as LANGUAGE_BIDI %}`` returns the current
  630. locale's direction. If ``True``, it's a right-to-left language, e.g. Hebrew,
  631. Arabic. If ``False`` it's a left-to-right language, e.g. English, French,
  632. German, etc.
  633. If you enable the ``django.template.context_processors.i18n`` context processor
  634. then each ``RequestContext`` will have access to ``LANGUAGES``,
  635. ``LANGUAGE_CODE``, and ``LANGUAGE_BIDI`` as defined above.
  636. .. templatetag:: get_language_info
  637. ``get_language_info``
  638. ~~~~~~~~~~~~~~~~~~~~~
  639. You can also retrieve information about any of the available languages using
  640. provided template tags and filters. To get information about a single language,
  641. use the ``{% get_language_info %}`` tag::
  642. {% get_language_info for LANGUAGE_CODE as lang %}
  643. {% get_language_info for "pl" as lang %}
  644. You can then access the information::
  645. Language code: {{ lang.code }}<br />
  646. Name of language: {{ lang.name_local }}<br />
  647. Name in English: {{ lang.name }}<br />
  648. Bi-directional: {{ lang.bidi }}
  649. Name in the active language: {{ lang.name_translated }}
  650. .. versionadded:: 1.9
  651. The ``name_translated`` attribute was added.
  652. .. templatetag:: get_language_info_list
  653. ``get_language_info_list``
  654. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  655. You can also use the ``{% get_language_info_list %}`` template tag to retrieve
  656. information for a list of languages (e.g. active languages as specified in
  657. :setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
  658. view <set_language-redirect-view>` for an example of how to display a language
  659. selector using ``{% get_language_info_list %}``.
  660. In addition to :setting:`LANGUAGES` style list of tuples,
  661. ``{% get_language_info_list %}`` supports simple lists of language codes.
  662. If you do this in your view:
  663. .. code-block:: python
  664. context = {'available_languages': ['en', 'es', 'fr']}
  665. return render(request, 'mytemplate.html', context)
  666. you can iterate over those languages in the template::
  667. {% get_language_info_list for available_languages as langs %}
  668. {% for lang in langs %} ... {% endfor %}
  669. .. templatefilter:: language_name
  670. .. templatefilter:: language_name_local
  671. .. templatefilter:: language_bidi
  672. .. templatefilter:: language_name_translated
  673. Template filters
  674. ~~~~~~~~~~~~~~~~
  675. There are also simple filters available for convenience:
  676. * ``{{ LANGUAGE_CODE|language_name }}`` ("German")
  677. * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
  678. * ``{{ LANGUAGE_CODE|language_bidi }}`` (False)
  679. * ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active language is Czech)
  680. .. versionadded:: 1.9
  681. The ``language_name_translated`` filter was added.
  682. .. _Django templates: ../templates_python/
  683. Internationalization: in JavaScript code
  684. ========================================
  685. .. highlightlang:: python
  686. Adding translations to JavaScript poses some problems:
  687. * JavaScript code doesn't have access to a ``gettext`` implementation.
  688. * JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to
  689. be delivered by the server.
  690. * The translation catalogs for JavaScript should be kept as small as
  691. possible.
  692. Django provides an integrated solution for these problems: It passes the
  693. translations into JavaScript, so you can call ``gettext``, etc., from within
  694. JavaScript.
  695. .. _javascript_catalog-view:
  696. The ``javascript_catalog`` view
  697. -------------------------------
  698. .. module:: django.views.i18n
  699. .. function:: javascript_catalog(request, domain='djangojs', packages=None)
  700. The main solution to these problems is the
  701. :meth:`django.views.i18n.javascript_catalog` view, which sends out a JavaScript
  702. code library with functions that mimic the ``gettext`` interface, plus an array
  703. of translation strings. Those translation strings are taken from applications or
  704. Django core, according to what you specify in either the ``info_dict`` or the
  705. URL. Paths listed in :setting:`LOCALE_PATHS` are also included.
  706. You hook it up like this::
  707. from django.views.i18n import javascript_catalog
  708. js_info_dict = {
  709. 'packages': ('your.app.package',),
  710. }
  711. urlpatterns = [
  712. url(r'^jsi18n/$', javascript_catalog, js_info_dict),
  713. ]
  714. Each string in ``packages`` should be in Python dotted-package syntax (the
  715. same format as the strings in :setting:`INSTALLED_APPS`) and should refer to a
  716. package that contains a ``locale`` directory. If you specify multiple packages,
  717. all those catalogs are merged into one catalog. This is useful if you have
  718. JavaScript that uses strings from different applications.
  719. The precedence of translations is such that the packages appearing later in the
  720. ``packages`` argument have higher precedence than the ones appearing at the
  721. beginning, this is important in the case of clashing translations for the same
  722. literal.
  723. By default, the view uses the ``djangojs`` gettext domain. This can be
  724. changed by altering the ``domain`` argument.
  725. You can make the view dynamic by putting the packages into the URL pattern::
  726. urlpatterns = [
  727. url(r'^jsi18n/(?P<packages>\S+?)/$', javascript_catalog),
  728. ]
  729. With this, you specify the packages as a list of package names delimited by '+'
  730. signs in the URL. This is especially useful if your pages use code from
  731. different apps and this changes often and you don't want to pull in one big
  732. catalog file. As a security measure, these values can only be either
  733. ``django.conf`` or any package from the :setting:`INSTALLED_APPS` setting.
  734. You can also split the catalogs in multiple URLs and load them as you need in
  735. your sites::
  736. js_info_dict_app = {
  737. 'packages': ('your.app.package',),
  738. }
  739. js_info_dict_other_app = {
  740. 'packages': ('your.other.app.package',),
  741. }
  742. urlpatterns = [
  743. url(r'^jsi18n/app/$', javascript_catalog, js_info_dict_app),
  744. url(r'^jsi18n/other_app/$', javascript_catalog, js_info_dict_other_app),
  745. ]
  746. If you use more than one ``javascript_catalog`` on a site and some of them
  747. define the same strings, the strings in the catalog that was loaded last take
  748. precedence.
  749. .. versionchanged:: 1.9
  750. Before Django 1.9, the catalogs completely overwrote each other and you
  751. could only use one at a time.
  752. The JavaScript translations found in the paths listed in the
  753. :setting:`LOCALE_PATHS` setting are also always included. To keep consistency
  754. with the translations lookup order algorithm used for Python and templates, the
  755. directories listed in :setting:`LOCALE_PATHS` have the highest precedence with
  756. the ones appearing first having higher precedence than the ones appearing
  757. later.
  758. Using the JavaScript translation catalog
  759. ----------------------------------------
  760. .. highlightlang:: javascript
  761. To use the catalog, just pull in the dynamically generated script like this:
  762. .. code-block:: html+django
  763. <script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script>
  764. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
  765. When the catalog is loaded, your JavaScript code can use the following methods:
  766. * ``gettext``
  767. * ``ngettext``
  768. * ``interpolate``
  769. * ``get_format``
  770. * ``gettext_noop``
  771. * ``pgettext``
  772. * ``npgettext``
  773. * ``pluralidx``
  774. ``gettext``
  775. ~~~~~~~~~~~
  776. The ``gettext`` function behaves similarly to the standard ``gettext``
  777. interface within your Python code::
  778. document.write(gettext('this is to be translated'));
  779. ``ngettext``
  780. ~~~~~~~~~~~~
  781. The ``ngettext`` function provides an interface to pluralize words and
  782. phrases::
  783. var object_count = 1 // or 0, or 2, or 3, ...
  784. s = ngettext('literal for the singular case',
  785. 'literal for the plural case', object_count);
  786. ``interpolate``
  787. ~~~~~~~~~~~~~~~
  788. The ``interpolate`` function supports dynamically populating a format string.
  789. The interpolation syntax is borrowed from Python, so the ``interpolate``
  790. function supports both positional and named interpolation:
  791. * Positional interpolation: ``obj`` contains a JavaScript Array object
  792. whose elements values are then sequentially interpolated in their
  793. corresponding ``fmt`` placeholders in the same order they appear.
  794. For example::
  795. fmts = ngettext('There is %s object. Remaining: %s',
  796. 'There are %s objects. Remaining: %s', 11);
  797. s = interpolate(fmts, [11, 20]);
  798. // s is 'There are 11 objects. Remaining: 20'
  799. * Named interpolation: This mode is selected by passing the optional
  800. boolean ``named`` parameter as ``true``. ``obj`` contains a JavaScript
  801. object or associative array. For example::
  802. d = {
  803. count: 10,
  804. total: 50
  805. };
  806. fmts = ngettext('Total: %(total)s, there is %(count)s object',
  807. 'there are %(count)s of a total of %(total)s objects', d.count);
  808. s = interpolate(fmts, d, true);
  809. You shouldn't go over the top with string interpolation, though: this is still
  810. JavaScript, so the code has to make repeated regular-expression substitutions.
  811. This isn't as fast as string interpolation in Python, so keep it to those
  812. cases where you really need it (for example, in conjunction with ``ngettext``
  813. to produce proper pluralizations).
  814. ``get_format``
  815. ~~~~~~~~~~~~~~
  816. The ``get_format`` function has access to the configured i18n formatting
  817. settings and can retrieve the format string for a given setting name::
  818. document.write(get_format('DATE_FORMAT'));
  819. // 'N j, Y'
  820. It has access to the following settings:
  821. * :setting:`DATE_FORMAT`
  822. * :setting:`DATE_INPUT_FORMATS`
  823. * :setting:`DATETIME_FORMAT`
  824. * :setting:`DATETIME_INPUT_FORMATS`
  825. * :setting:`DECIMAL_SEPARATOR`
  826. * :setting:`FIRST_DAY_OF_WEEK`
  827. * :setting:`MONTH_DAY_FORMAT`
  828. * :setting:`NUMBER_GROUPING`
  829. * :setting:`SHORT_DATE_FORMAT`
  830. * :setting:`SHORT_DATETIME_FORMAT`
  831. * :setting:`THOUSAND_SEPARATOR`
  832. * :setting:`TIME_FORMAT`
  833. * :setting:`TIME_INPUT_FORMATS`
  834. * :setting:`YEAR_MONTH_FORMAT`
  835. This is useful for maintaining formatting consistency with the Python-rendered
  836. values.
  837. ``gettext_noop``
  838. ~~~~~~~~~~~~~~~~
  839. This emulates the ``gettext`` function but does nothing, returning whatever
  840. is passed to it::
  841. document.write(gettext_noop('this will not be translated'));
  842. This is useful for stubbing out portions of the code that will need translation
  843. in the future.
  844. ``pgettext``
  845. ~~~~~~~~~~~~
  846. The ``pgettext`` function behaves like the Python variant
  847. (:func:`~django.utils.translation.pgettext()`), providing a contextually
  848. translated word::
  849. document.write(pgettext('month name', 'May'));
  850. ``npgettext``
  851. ~~~~~~~~~~~~~
  852. The ``npgettext`` function also behaves like the Python variant
  853. (:func:`~django.utils.translation.npgettext()`), providing a **pluralized**
  854. contextually translated word::
  855. document.write(npgettext('group', 'party', 1));
  856. // party
  857. document.write(npgettext('group', 'party', 2));
  858. // parties
  859. ``pluralidx``
  860. ~~~~~~~~~~~~~
  861. The ``pluralidx`` function works in a similar way to the :tfilter:`pluralize`
  862. template filter, determining if a given ``count`` should use a plural form of
  863. a word or not::
  864. document.write(pluralidx(0));
  865. // true
  866. document.write(pluralidx(1));
  867. // false
  868. document.write(pluralidx(2));
  869. // true
  870. In the simplest case, if no custom pluralization is needed, this returns
  871. ``false`` for the integer ``1`` and ``true`` for all other numbers.
  872. However, pluralization is not this simple in all languages. If the language does
  873. not support pluralization, an empty value is provided.
  874. Additionally, if there are complex rules around pluralization, the catalog view
  875. will render a conditional expression. This will evaluate to either a ``true``
  876. (should pluralize) or ``false`` (should **not** pluralize) value.
  877. The ``json_catalog`` view
  878. -------------------------
  879. .. versionadded:: 1.9
  880. .. function:: json_catalog(request, domain='djangojs', packages=None)
  881. In order to use another client-side library to handle translations, you may
  882. want to take advantage of the ``json_catalog()`` view. It's similar to
  883. :meth:`~django.views.i18n.javascript_catalog` but returns a JSON response.
  884. The JSON object contains i18n formatting settings (those available for
  885. `get_format`_), a plural rule (as a ``plural`` part of a GNU gettext
  886. ``Plural-Forms`` expression), and translation strings. The translation strings
  887. are taken from applications or Django's own translations, according to what is
  888. specified either via ``urlpatterns`` arguments or as request parameters. Paths
  889. listed in :setting:`LOCALE_PATHS` are also included.
  890. The view is hooked up to your application and configured in the same fashion as
  891. :meth:`~django.views.i18n.javascript_catalog` (namely, the ``domain`` and
  892. ``packages`` arguments behave identically)::
  893. from django.views.i18n import json_catalog
  894. js_info_dict = {
  895. 'packages': ('your.app.package',),
  896. }
  897. urlpatterns = [
  898. url(r'^jsoni18n/$', json_catalog, js_info_dict),
  899. ]
  900. The response format is as follows:
  901. .. code-block:: json
  902. {
  903. "catalog": {
  904. # Translations catalog
  905. },
  906. "formats": {
  907. # Language formats for date, time, etc.
  908. },
  909. "plural": "..." # Expression for plural forms, or null.
  910. }
  911. Note on performance
  912. -------------------
  913. The :func:`~django.views.i18n.javascript_catalog` view generates the catalog
  914. from ``.mo`` files on every request. Since its output is constant — at least
  915. for a given version of a site — it's a good candidate for caching.
  916. Server-side caching will reduce CPU load. It's easily implemented with the
  917. :func:`~django.views.decorators.cache.cache_page` decorator. To trigger cache
  918. invalidation when your translations change, provide a version-dependent key
  919. prefix, as shown in the example below, or map the view at a version-dependent
  920. URL.
  921. .. code-block:: python
  922. from django.views.decorators.cache import cache_page
  923. from django.views.i18n import javascript_catalog
  924. # The value returned by get_version() must change when translations change.
  925. @cache_page(86400, key_prefix='js18n-%s' % get_version())
  926. def cached_javascript_catalog(request, domain='djangojs', packages=None):
  927. return javascript_catalog(request, domain, packages)
  928. Client-side caching will save bandwidth and make your site load faster. If
  929. you're using ETags (:setting:`USE_ETAGS = True <USE_ETAGS>`), you're already
  930. covered. Otherwise, you can apply :ref:`conditional decorators
  931. <conditional-decorators>`. In the following example, the cache is invalidated
  932. whenever you restart your application server.
  933. .. code-block:: python
  934. from django.utils import timezone
  935. from django.views.decorators.http import last_modified
  936. from django.views.i18n import javascript_catalog
  937. last_modified_date = timezone.now()
  938. @last_modified(lambda req, **kw: last_modified_date)
  939. def cached_javascript_catalog(request, domain='djangojs', packages=None):
  940. return javascript_catalog(request, domain, packages)
  941. You can even pre-generate the JavaScript catalog as part of your deployment
  942. procedure and serve it as a static file. This radical technique is implemented
  943. in django-statici18n_.
  944. .. _django-statici18n: http://django-statici18n.readthedocs.org/en/latest/
  945. .. _url-internationalization:
  946. Internationalization: in URL patterns
  947. =====================================
  948. .. module:: django.conf.urls.i18n
  949. Django provides two mechanisms to internationalize URL patterns:
  950. * Adding the language prefix to the root of the URL patterns to make it
  951. possible for :class:`~django.middleware.locale.LocaleMiddleware` to detect
  952. the language to activate from the requested URL.
  953. * Making URL patterns themselves translatable via the
  954. :func:`django.utils.translation.ugettext_lazy()` function.
  955. .. warning::
  956. Using either one of these features requires that an active language be set
  957. for each request; in other words, you need to have
  958. :class:`django.middleware.locale.LocaleMiddleware` in your
  959. :setting:`MIDDLEWARE_CLASSES` setting.
  960. Language prefix in URL patterns
  961. -------------------------------
  962. .. function:: i18n_patterns(*pattern_list)
  963. This function can be used in your root URLconf and Django will automatically
  964. prepend the current active language code to all url patterns defined within
  965. :func:`~django.conf.urls.i18n.i18n_patterns`. Example URL patterns::
  966. from django.conf.urls import include, url
  967. from django.conf.urls.i18n import i18n_patterns
  968. from about import views as about_views
  969. from news import views as news_views
  970. from sitemap.views import sitemap
  971. urlpatterns = [
  972. url(r'^sitemap\.xml$', sitemap, name='sitemap_xml'),
  973. ]
  974. news_patterns = ([
  975. url(r'^$', news_views.index, name='index'),
  976. url(r'^category/(?P<slug>[\w-]+)/$', news_views.category, name='category'),
  977. url(r'^(?P<slug>[\w-]+)/$', news_views.details, name='detail'),
  978. ], 'news')
  979. urlpatterns += i18n_patterns(
  980. url(r'^about/$', about_views.main, name='about'),
  981. url(r'^news/', include(news_patterns, namespace='news')),
  982. )
  983. After defining these URL patterns, Django will automatically add the
  984. language prefix to the URL patterns that were added by the ``i18n_patterns``
  985. function. Example::
  986. from django.core.urlresolvers import reverse
  987. from django.utils.translation import activate
  988. >>> activate('en')
  989. >>> reverse('sitemap_xml')
  990. '/sitemap.xml'
  991. >>> reverse('news:index')
  992. '/en/news/'
  993. >>> activate('nl')
  994. >>> reverse('news:detail', kwargs={'slug': 'news-slug'})
  995. '/nl/news/news-slug/'
  996. .. warning::
  997. :func:`~django.conf.urls.i18n.i18n_patterns` is only allowed in your root
  998. URLconf. Using it within an included URLconf will throw an
  999. :exc:`~django.core.exceptions.ImproperlyConfigured` exception.
  1000. .. warning::
  1001. Ensure that you don't have non-prefixed URL patterns that might collide
  1002. with an automatically-added language prefix.
  1003. Translating URL patterns
  1004. ------------------------
  1005. URL patterns can also be marked translatable using the
  1006. :func:`~django.utils.translation.ugettext_lazy` function. Example::
  1007. from django.conf.urls import include, url
  1008. from django.conf.urls.i18n import i18n_patterns
  1009. from django.utils.translation import ugettext_lazy as _
  1010. from about import views as about_views
  1011. from news import views as news_views
  1012. from sitemaps.views import sitemap
  1013. urlpatterns = [
  1014. url(r'^sitemap\.xml$', sitemap, name='sitemap_xml'),
  1015. ]
  1016. news_patterns = ([
  1017. url(r'^$', news_views.index, name='index'),
  1018. url(_(r'^category/(?P<slug>[\w-]+)/$'), news_views.category, name='category'),
  1019. url(r'^(?P<slug>[\w-]+)/$', news_views.details, name='detail'),
  1020. ], 'news')
  1021. urlpatterns += i18n_patterns(
  1022. url(_(r'^about/$'), about_views.main, name='about'),
  1023. url(_(r'^news/'), include(news_patterns, namespace='news')),
  1024. )
  1025. After you've created the translations, the
  1026. :func:`~django.core.urlresolvers.reverse` function will return the URL in the
  1027. active language. Example::
  1028. from django.core.urlresolvers import reverse
  1029. from django.utils.translation import activate
  1030. >>> activate('en')
  1031. >>> reverse('news:category', kwargs={'slug': 'recent'})
  1032. '/en/news/category/recent/'
  1033. >>> activate('nl')
  1034. >>> reverse('news:category', kwargs={'slug': 'recent'})
  1035. '/nl/nieuws/categorie/recent/'
  1036. .. warning::
  1037. In most cases, it's best to use translated URLs only within a
  1038. language-code-prefixed block of patterns (using
  1039. :func:`~django.conf.urls.i18n.i18n_patterns`), to avoid the possibility
  1040. that a carelessly translated URL causes a collision with a non-translated
  1041. URL pattern.
  1042. .. _reversing_in_templates:
  1043. Reversing in templates
  1044. ----------------------
  1045. If localized URLs get reversed in templates they always use the current
  1046. language. To link to a URL in another language use the :ttag:`language`
  1047. template tag. It enables the given language in the enclosed template section:
  1048. .. code-block:: html+django
  1049. {% load i18n %}
  1050. {% get_available_languages as languages %}
  1051. {% trans "View this category in:" %}
  1052. {% for lang_code, lang_name in languages %}
  1053. {% language lang_code %}
  1054. <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}</a>
  1055. {% endlanguage %}
  1056. {% endfor %}
  1057. The :ttag:`language` tag expects the language code as the only argument.
  1058. .. _how-to-create-language-files:
  1059. Localization: how to create language files
  1060. ==========================================
  1061. Once the string literals of an application have been tagged for later
  1062. translation, the translation themselves need to be written (or obtained). Here's
  1063. how that works.
  1064. Message files
  1065. -------------
  1066. The first step is to create a :term:`message file` for a new language. A message
  1067. file is a plain-text file, representing a single language, that contains all
  1068. available translation strings and how they should be represented in the given
  1069. language. Message files have a ``.po`` file extension.
  1070. Django comes with a tool, :djadmin:`django-admin makemessages
  1071. <makemessages>`, that automates the creation and upkeep of these files.
  1072. .. admonition:: Gettext utilities
  1073. The ``makemessages`` command (and ``compilemessages`` discussed later) use
  1074. commands from the GNU gettext toolset: ``xgettext``, ``msgfmt``,
  1075. ``msgmerge`` and ``msguniq``.
  1076. The minimum version of the ``gettext`` utilities supported is 0.15.
  1077. To create or update a message file, run this command::
  1078. django-admin makemessages -l de
  1079. ...where ``de`` is the :term:`locale name` for the message file you want to
  1080. create. For example, ``pt_BR`` for Brazilian Portuguese, ``de_AT`` for Austrian
  1081. German or ``id`` for Indonesian.
  1082. The script should be run from one of two places:
  1083. * The root directory of your Django project (the one that contains
  1084. ``manage.py``).
  1085. * The root directory of one of your Django apps.
  1086. The script runs over your project source tree or your application source tree
  1087. and pulls out all strings marked for translation (see
  1088. :ref:`how-django-discovers-translations` and be sure :setting:`LOCALE_PATHS`
  1089. is configured correctly). It creates (or updates) a message file in the
  1090. directory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the file will be
  1091. ``locale/de/LC_MESSAGES/django.po``.
  1092. When you run ``makemessages`` from the root directory of your project, the
  1093. extracted strings will be automatically distributed to the proper message files.
  1094. That is, a string extracted from a file of an app containing a ``locale``
  1095. directory will go in a message file under that directory. A string extracted
  1096. from a file of an app without any ``locale`` directory will either go in a
  1097. message file under the directory listed first in :setting:`LOCALE_PATHS` or
  1098. will generate an error if :setting:`LOCALE_PATHS` is empty.
  1099. By default :djadmin:`django-admin makemessages <makemessages>` examines every
  1100. file that has the ``.html`` or ``.txt`` file extension. In case you want to
  1101. override that default, use the ``--extension`` or ``-e`` option to specify the
  1102. file extensions to examine::
  1103. django-admin makemessages -l de -e txt
  1104. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
  1105. multiple times::
  1106. django-admin makemessages -l de -e html,txt -e xml
  1107. .. warning::
  1108. When :ref:`creating message files from JavaScript source code
  1109. <creating-message-files-from-js-code>` you need to use the special
  1110. 'djangojs' domain, **not** ``-e js``.
  1111. .. admonition:: Using Jinja2 templates?
  1112. :djadmin:`makemessages` doesn't understand the syntax of Jinja2 templates.
  1113. To extract strings from a project containing Jinja2 templates, use `Message
  1114. Extracting`_ from Babel_ instead.
  1115. Here's an example ``babel.cfg`` configuration file::
  1116. # Extraction from Python source files
  1117. [python: **.py]
  1118. # Extraction from Jinja2 templates
  1119. [jinja2: **.jinja]
  1120. extensions = jinja2.ext.with_
  1121. Make sure you list all extensions you're using! Otherwise Babel won't
  1122. recognize the tags defined by these extensions and will ignore Jinja2
  1123. templates containing them entirely.
  1124. Babel provides similar features to :djadmin:`makemessages`, can replace it
  1125. in general, and doesn't depend on ``gettext``. For more information, read
  1126. its documentation about `working with message catalogs`_.
  1127. .. _Message extracting: http://babel.pocoo.org/docs/messages/#message-extraction
  1128. .. _Babel: http://babel.pocoo.org/
  1129. .. _working with message catalogs: http://babel.pocoo.org/docs/messages/
  1130. .. admonition:: No gettext?
  1131. If you don't have the ``gettext`` utilities installed,
  1132. :djadmin:`makemessages` will create empty files. If that's the case, either
  1133. install the ``gettext`` utilities or just copy the English message file
  1134. (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
  1135. point; it's just an empty translation file.
  1136. .. admonition:: Working on Windows?
  1137. If you're using Windows and need to install the GNU gettext utilities so
  1138. :djadmin:`makemessages` works, see :ref:`gettext_on_windows` for more
  1139. information.
  1140. The format of ``.po`` files is straightforward. Each ``.po`` file contains a
  1141. small bit of metadata, such as the translation maintainer's contact
  1142. information, but the bulk of the file is a list of **messages** -- simple
  1143. mappings between translation strings and the actual translated text for the
  1144. particular language.
  1145. For example, if your Django app contained a translation string for the text
  1146. ``"Welcome to my site."``, like so::
  1147. _("Welcome to my site.")
  1148. ...then :djadmin:`django-admin makemessages <makemessages>` will have created
  1149. a ``.po`` file containing the following snippet -- a message:
  1150. .. code-block:: po
  1151. #: path/to/python/module.py:23
  1152. msgid "Welcome to my site."
  1153. msgstr ""
  1154. A quick explanation:
  1155. * ``msgid`` is the translation string, which appears in the source. Don't
  1156. change it.
  1157. * ``msgstr`` is where you put the language-specific translation. It starts
  1158. out empty, so it's your responsibility to change it. Make sure you keep
  1159. the quotes around your translation.
  1160. * As a convenience, each message includes, in the form of a comment line
  1161. prefixed with ``#`` and located above the ``msgid`` line, the filename and
  1162. line number from which the translation string was gleaned.
  1163. Long messages are a special case. There, the first string directly after the
  1164. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
  1165. written over the next few lines as one string per line. Those strings are
  1166. directly concatenated. Don't forget trailing spaces within the strings;
  1167. otherwise, they'll be tacked together without whitespace!
  1168. .. admonition:: Mind your charset
  1169. Due to the way the ``gettext`` tools work internally and because we want to
  1170. allow non-ASCII source strings in Django's core and your applications, you
  1171. **must** use UTF-8 as the encoding for your PO files (the default when PO
  1172. files are created). This means that everybody will be using the same
  1173. encoding, which is important when Django processes the PO files.
  1174. To reexamine all source code and templates for new translation strings and
  1175. update all message files for **all** languages, run this::
  1176. django-admin makemessages -a
  1177. Compiling message files
  1178. -----------------------
  1179. After you create your message file -- and each time you make changes to it --
  1180. you'll need to compile it into a more efficient form, for use by ``gettext``. Do
  1181. this with the :djadmin:`django-admin compilemessages <compilemessages>`
  1182. utility.
  1183. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
  1184. are binary files optimized for use by ``gettext``. In the same directory from
  1185. which you ran :djadmin:`django-admin makemessages <makemessages>`, run
  1186. :djadmin:`django-admin compilemessages <compilemessages>` like this::
  1187. django-admin compilemessages
  1188. That's it. Your translations are ready for use.
  1189. .. versionchanged:: 1.9
  1190. ``compilemessages`` now matches the operation of :djadmin:`makemessages`,
  1191. scanning the project tree for ``.po`` files to compile.
  1192. .. admonition:: Working on Windows?
  1193. If you're using Windows and need to install the GNU gettext utilities so
  1194. :djadmin:`django-admin compilemessages <compilemessages>` works see
  1195. :ref:`gettext_on_windows` for more information.
  1196. .. admonition:: .po files: Encoding and BOM usage.
  1197. Django only supports ``.po`` files encoded in UTF-8 and without any BOM
  1198. (Byte Order Mark) so if your text editor adds such marks to the beginning of
  1199. files by default then you will need to reconfigure it.
  1200. .. _creating-message-files-from-js-code:
  1201. Creating message files from JavaScript source code
  1202. --------------------------------------------------
  1203. You create and update the message files the same way as the other Django message
  1204. files -- with the :djadmin:`django-admin makemessages <makemessages>` tool.
  1205. The only difference is you need to explicitly specify what in gettext parlance
  1206. is known as a domain in this case the ``djangojs`` domain, by providing a ``-d
  1207. djangojs`` parameter, like this::
  1208. django-admin makemessages -d djangojs -l de
  1209. This would create or update the message file for JavaScript for German. After
  1210. updating message files, just run :djadmin:`django-admin compilemessages
  1211. <compilemessages>` the same way as you do with normal Django message files.
  1212. .. _gettext_on_windows:
  1213. ``gettext`` on Windows
  1214. ----------------------
  1215. This is only needed for people who either want to extract message IDs or compile
  1216. message files (``.po``). Translation work itself just involves editing existing
  1217. files of this type, but if you want to create your own message files, or want to
  1218. test or compile a changed message file, you will need the ``gettext`` utilities:
  1219. * Download the following zip files from the GNOME servers
  1220. https://download.gnome.org/binaries/win32/dependencies/
  1221. * ``gettext-runtime-X.zip``
  1222. * ``gettext-tools-X.zip``
  1223. ``X`` is the version number, we are requiring ``0.15`` or higher.
  1224. * Extract the contents of the ``bin\`` directories in both files to the
  1225. same folder on your system (i.e. ``C:\Program Files\gettext-utils``)
  1226. * Update the system PATH:
  1227. * ``Control Panel > System > Advanced > Environment Variables``.
  1228. * In the ``System variables`` list, click ``Path``, click ``Edit``.
  1229. * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
  1230. ``Variable value`` field.
  1231. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
  1232. the ``xgettext --version`` command works properly. Do not attempt to use Django
  1233. translation utilities with a ``gettext`` package if the command ``xgettext
  1234. --version`` entered at a Windows command prompt causes a popup window saying
  1235. "xgettext.exe has generated errors and will be closed by Windows".
  1236. .. _customizing-makemessages:
  1237. Customizing the ``makemessages`` command
  1238. ----------------------------------------
  1239. .. highlightlang:: python
  1240. If you want to pass additional parameters to ``xgettext``, you need to create a
  1241. custom :djadmin:`makemessages` command and override its ``xgettext_options``
  1242. attribute::
  1243. from django.core.management.commands import makemessages
  1244. class Command(makemessages.Command):
  1245. xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']
  1246. If you need more flexibility, you could also add a new argument to your custom
  1247. :djadmin:`makemessages` command::
  1248. from django.core.management.commands import makemessages
  1249. class Command(makemessages.Command):
  1250. def add_arguments(self, parser):
  1251. super(Command, self).add_arguments(parser)
  1252. parser.add_argument('--extra-keyword', dest='xgettext_keywords',
  1253. action='append')
  1254. def handle(self, *args, **options):
  1255. xgettext_keywords = options.pop('xgettext_keywords')
  1256. if xgettext_keywords:
  1257. self.xgettext_options = (
  1258. makemessages.Command.xgettext_options[:] +
  1259. ['--keyword=%s' % kwd for kwd in xgettext_keywords]
  1260. )
  1261. super(Command, self).handle(*args, **options)
  1262. Miscellaneous
  1263. =============
  1264. .. _set_language-redirect-view:
  1265. The ``set_language`` redirect view
  1266. ----------------------------------
  1267. .. highlightlang:: python
  1268. .. currentmodule:: django.views.i18n
  1269. .. function:: set_language(request)
  1270. As a convenience, Django comes with a view, :func:`django.views.i18n.set_language`,
  1271. that sets a user's language preference and redirects to a given URL or, by default,
  1272. back to the previous page.
  1273. Activate this view by adding the following line to your URLconf::
  1274. url(r'^i18n/', include('django.conf.urls.i18n')),
  1275. (Note that this example makes the view available at ``/i18n/setlang/``.)
  1276. .. warning::
  1277. Make sure that you don't include the above URL within
  1278. :func:`~django.conf.urls.i18n.i18n_patterns` - it needs to be
  1279. language-independent itself to work correctly.
  1280. The view expects to be called via the ``POST`` method, with a ``language``
  1281. parameter set in request. If session support is enabled, the view
  1282. saves the language choice in the user's session. Otherwise, it saves the
  1283. language choice in a cookie that is by default named ``django_language``.
  1284. (The name can be changed through the :setting:`LANGUAGE_COOKIE_NAME` setting.)
  1285. After setting the language choice, Django redirects the user, following this
  1286. algorithm:
  1287. * Django looks for a ``next`` parameter in the ``POST`` data.
  1288. * If that doesn't exist, or is empty, Django tries the URL in the
  1289. ``Referrer`` header.
  1290. * If that's empty -- say, if a user's browser suppresses that header --
  1291. then the user will be redirected to ``/`` (the site root) as a fallback.
  1292. Here's example HTML template code:
  1293. .. code-block:: html+django
  1294. {% load i18n %}
  1295. <form action="{% url 'set_language' %}" method="post">{% csrf_token %}
  1296. <input name="next" type="hidden" value="{{ redirect_to }}" />
  1297. <select name="language">
  1298. {% get_current_language as LANGUAGE_CODE %}
  1299. {% get_available_languages as LANGUAGES %}
  1300. {% get_language_info_list for LANGUAGES as languages %}
  1301. {% for language in languages %}
  1302. <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
  1303. {{ language.name_local }} ({{ language.code }})
  1304. </option>
  1305. {% endfor %}
  1306. </select>
  1307. <input type="submit" value="Go" />
  1308. </form>
  1309. In this example, Django looks up the URL of the page to which the user will be
  1310. redirected in the ``redirect_to`` context variable.
  1311. Explicitly setting the active language
  1312. --------------------------------------
  1313. .. highlightlang:: python
  1314. You may want to set the active language for the current session explicitly. Perhaps
  1315. a user's language preference is retrieved from another system, for example.
  1316. You've already been introduced to :func:`django.utils.translation.activate()`. That
  1317. applies to the current thread only. To persist the language for the entire
  1318. session, also modify :data:`~django.utils.translation.LANGUAGE_SESSION_KEY`
  1319. in the session::
  1320. from django.utils import translation
  1321. user_language = 'fr'
  1322. translation.activate(user_language)
  1323. request.session[translation.LANGUAGE_SESSION_KEY] = user_language
  1324. You would typically want to use both: :func:`django.utils.translation.activate()`
  1325. will change the language for this thread, and modifying the session makes this
  1326. preference persist in future requests.
  1327. If you are not using sessions, the language will persist in a cookie, whose name
  1328. is configured in :setting:`LANGUAGE_COOKIE_NAME`. For example::
  1329. from django.utils import translation
  1330. from django import http
  1331. from django.conf import settings
  1332. user_language = 'fr'
  1333. translation.activate(user_language)
  1334. response = http.HttpResponse(...)
  1335. response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
  1336. Using translations outside views and templates
  1337. ----------------------------------------------
  1338. While Django provides a rich set of i18n tools for use in views and templates,
  1339. it does not restrict the usage to Django-specific code. The Django translation
  1340. mechanisms can be used to translate arbitrary texts to any language that is
  1341. supported by Django (as long as an appropriate translation catalog exists, of
  1342. course). You can load a translation catalog, activate it and translate text to
  1343. language of your choice, but remember to switch back to original language, as
  1344. activating a translation catalog is done on per-thread basis and such change
  1345. will affect code running in the same thread.
  1346. For example::
  1347. from django.utils import translation
  1348. def welcome_translated(language):
  1349. cur_language = translation.get_language()
  1350. try:
  1351. translation.activate(language)
  1352. text = translation.ugettext('welcome')
  1353. finally:
  1354. translation.activate(cur_language)
  1355. return text
  1356. Calling this function with the value 'de' will give you ``"Willkommen"``,
  1357. regardless of :setting:`LANGUAGE_CODE` and language set by middleware.
  1358. Functions of particular interest are ``django.utils.translation.get_language()``
  1359. which returns the language used in the current thread,
  1360. ``django.utils.translation.activate()`` which activates a translation catalog
  1361. for the current thread, and ``django.utils.translation.check_for_language()``
  1362. which checks if the given language is supported by Django.
  1363. To help write more concise code, there is also a context manager
  1364. ``django.utils.translation.override()`` that stores the current language on
  1365. enter and restores it on exit. With it, the above example becomes::
  1366. from django.utils import translation
  1367. def welcome_translated(language):
  1368. with translation.override(language):
  1369. return translation.ugettext('welcome')
  1370. Language cookie
  1371. ---------------
  1372. A number of settings can be used to adjust language cookie options:
  1373. * :setting:`LANGUAGE_COOKIE_NAME`
  1374. * :setting:`LANGUAGE_COOKIE_AGE`
  1375. * :setting:`LANGUAGE_COOKIE_DOMAIN`
  1376. * :setting:`LANGUAGE_COOKIE_PATH`
  1377. Implementation notes
  1378. ====================
  1379. .. _specialties-of-django-i18n:
  1380. Specialties of Django translation
  1381. ---------------------------------
  1382. Django's translation machinery uses the standard ``gettext`` module that comes
  1383. with Python. If you know ``gettext``, you might note these specialties in the
  1384. way Django does translation:
  1385. * The string domain is ``django`` or ``djangojs``. This string domain is
  1386. used to differentiate between different programs that store their data
  1387. in a common message-file library (usually ``/usr/share/locale/``). The
  1388. ``django`` domain is used for Python and template translation strings
  1389. and is loaded into the global translation catalogs. The ``djangojs``
  1390. domain is only used for JavaScript translation catalogs to make sure
  1391. that those are as small as possible.
  1392. * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
  1393. ``xgettext`` and ``msgfmt``. This is mostly for convenience.
  1394. .. _how-django-discovers-language-preference:
  1395. How Django discovers language preference
  1396. ----------------------------------------
  1397. Once you've prepared your translations -- or, if you just want to use the
  1398. translations that come with Django -- you'll just need to activate translation
  1399. for your app.
  1400. Behind the scenes, Django has a very flexible model of deciding which language
  1401. should be used -- installation-wide, for a particular user, or both.
  1402. To set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.
  1403. Django uses this language as the default translation -- the final attempt if no
  1404. better matching translation is found through one of the methods employed by the
  1405. locale middleware (see below).
  1406. If all you want is to run Django with your native language all you need to do
  1407. is set :setting:`LANGUAGE_CODE` and make sure the corresponding :term:`message
  1408. files <message file>` and their compiled versions (``.mo``) exist.
  1409. If you want to let each individual user specify which language they
  1410. prefer, then you also need to use the ``LocaleMiddleware``.
  1411. ``LocaleMiddleware`` enables language selection based on data from the request.
  1412. It customizes content for each user.
  1413. To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
  1414. to your :setting:`MIDDLEWARE_CLASSES` setting. Because middleware order
  1415. matters, you should follow these guidelines:
  1416. * Make sure it's one of the first middlewares installed.
  1417. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
  1418. makes use of session data. And it should come before ``CommonMiddleware``
  1419. because ``CommonMiddleware`` needs an activated language in order
  1420. to resolve the requested URL.
  1421. * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
  1422. For example, your :setting:`MIDDLEWARE_CLASSES` might look like this::
  1423. MIDDLEWARE_CLASSES = [
  1424. 'django.contrib.sessions.middleware.SessionMiddleware',
  1425. 'django.middleware.locale.LocaleMiddleware',
  1426. 'django.middleware.common.CommonMiddleware',
  1427. ]
  1428. (For more on middleware, see the :doc:`middleware documentation
  1429. </topics/http/middleware>`.)
  1430. ``LocaleMiddleware`` tries to determine the user's language preference by
  1431. following this algorithm:
  1432. * First, it looks for the language prefix in the requested URL. This is
  1433. only performed when you are using the ``i18n_patterns`` function in your
  1434. root URLconf. See :ref:`url-internationalization` for more information
  1435. about the language prefix and how to internationalize URL patterns.
  1436. * Failing that, it looks for the :data:`~django.utils.translation.LANGUAGE_SESSION_KEY`
  1437. key in the current user's session.
  1438. * Failing that, it looks for a cookie.
  1439. The name of the cookie used is set by the :setting:`LANGUAGE_COOKIE_NAME`
  1440. setting. (The default name is ``django_language``.)
  1441. * Failing that, it looks at the ``Accept-Language`` HTTP header. This
  1442. header is sent by your browser and tells the server which language(s) you
  1443. prefer, in order by priority. Django tries each language in the header
  1444. until it finds one with available translations.
  1445. * Failing that, it uses the global :setting:`LANGUAGE_CODE` setting.
  1446. .. _locale-middleware-notes:
  1447. Notes:
  1448. * In each of these places, the language preference is expected to be in the
  1449. standard :term:`language format<language code>`, as a string. For example,
  1450. Brazilian Portuguese is ``pt-br``.
  1451. * If a base language is available but the sublanguage specified is not,
  1452. Django uses the base language. For example, if a user specifies ``de-at``
  1453. (Austrian German) but Django only has ``de`` available, Django uses
  1454. ``de``.
  1455. * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
  1456. If you want to restrict the language selection to a subset of provided
  1457. languages (because your application doesn't provide all those languages),
  1458. set :setting:`LANGUAGES` to a list of languages. For example::
  1459. LANGUAGES = [
  1460. ('de', _('German')),
  1461. ('en', _('English')),
  1462. ]
  1463. This example restricts languages that are available for automatic
  1464. selection to German and English (and any sublanguage, like de-ch or
  1465. en-us).
  1466. * If you define a custom :setting:`LANGUAGES` setting, as explained in the
  1467. previous bullet, you can mark the language names as translation strings
  1468. -- but use :func:`~django.utils.translation.ugettext_lazy` instead of
  1469. :func:`~django.utils.translation.ugettext` to avoid a circular import.
  1470. Here's a sample settings file::
  1471. from django.utils.translation import ugettext_lazy as _
  1472. LANGUAGES = [
  1473. ('de', _('German')),
  1474. ('en', _('English')),
  1475. ]
  1476. Once ``LocaleMiddleware`` determines the user's preference, it makes this
  1477. preference available as ``request.LANGUAGE_CODE`` for each
  1478. :class:`~django.http.HttpRequest`. Feel free to read this value in your view
  1479. code. Here's a simple example::
  1480. from django.http import HttpResponse
  1481. def hello_world(request, count):
  1482. if request.LANGUAGE_CODE == 'de-at':
  1483. return HttpResponse("You prefer to read Austrian German.")
  1484. else:
  1485. return HttpResponse("You prefer to read another language.")
  1486. Note that, with static (middleware-less) translation, the language is in
  1487. ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
  1488. in ``request.LANGUAGE_CODE``.
  1489. .. _settings file: ../settings/
  1490. .. _middleware documentation: ../middleware/
  1491. .. _session: ../sessions/
  1492. .. _request object: ../request_response/#httprequest-objects
  1493. .. _how-django-discovers-translations:
  1494. How Django discovers translations
  1495. ---------------------------------
  1496. At runtime, Django builds an in-memory unified catalog of literals-translations.
  1497. To achieve this it looks for translations by following this algorithm regarding
  1498. the order in which it examines the different file paths to load the compiled
  1499. :term:`message files <message file>` (``.mo``) and the precedence of multiple
  1500. translations for the same literal:
  1501. 1. The directories listed in :setting:`LOCALE_PATHS` have the highest
  1502. precedence, with the ones appearing first having higher precedence than
  1503. the ones appearing later.
  1504. 2. Then, it looks for and uses if it exists a ``locale`` directory in each
  1505. of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
  1506. appearing first have higher precedence than the ones appearing later.
  1507. 3. Finally, the Django-provided base translation in ``django/conf/locale``
  1508. is used as a fallback.
  1509. .. seealso::
  1510. The translations for literals included in JavaScript assets are looked up
  1511. following a similar but not identical algorithm. See the
  1512. :ref:`javascript_catalog view documentation <javascript_catalog-view>` for
  1513. more details.
  1514. In all cases the name of the directory containing the translation is expected to
  1515. be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, ``es_AR``,
  1516. etc.
  1517. This way, you can write applications that include their own translations, and
  1518. you can override base translations in your project. Or, you can just build
  1519. a big project out of several apps and put all translations into one big common
  1520. message file specific to the project you are composing. The choice is yours.
  1521. All message file repositories are structured the same way. They are:
  1522. * All paths listed in :setting:`LOCALE_PATHS` in your settings file are
  1523. searched for ``<language>/LC_MESSAGES/django.(po|mo)``
  1524. * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
  1525. * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
  1526. To create message files, you use the :djadmin:`django-admin makemessages <makemessages>`
  1527. tool. And you use :djadmin:`django-admin compilemessages <compilemessages>`
  1528. to produce the binary ``.mo`` files that are used by ``gettext``.
  1529. You can also run :djadmin:`django-admin compilemessages
  1530. --settings=path.to.settings <compilemessages>` to make the compiler process all
  1531. the directories in your :setting:`LOCALE_PATHS` setting.