translation.txt 76 KB

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