translation.txt 75 KB

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