translation.txt 77 KB

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