PageRenderTime 34ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

Plain Text | 410 lines | 284 code | 126 blank | 0 comment | 0 complexity | 39152843de8c19c640ab081ca2c154d2 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. ============
  2. Localization
  3. ============
  4. This document covers three localization-related topics: `Creating language
  5. files`_ , `locale aware date, time and numbers input/output in forms`_,
  6. and `controlling localization in templates`_.
  7. .. _`Creating language files`: how-to-create-language-files_
  8. .. _`locale aware date, time and numbers input/output in forms`: format-localization_
  9. .. _`controlling localization in templates`: topic-l10n-templates_
  10. .. seealso::
  11. The :doc:`/howto/i18n` document included with the Django HOW-TO documents collection.
  12. .. _how-to-create-language-files:
  13. How to create language files
  14. ============================
  15. Once the string literals of an application have been tagged for later
  16. translation, the translation themselves need to be written (or obtained). Here's
  17. how that works.
  18. .. _locale-restrictions:
  19. .. admonition:: Locale restrictions
  20. Django does not support localizing your application into a locale for which
  21. Django itself has not been translated. In this case, it will ignore your
  22. translation files. If you were to try this and Django supported it, you
  23. would inevitably see a mixture of translated strings (from your application)
  24. and English strings (from Django itself). If you want to support a locale
  25. for your application that is not already part of Django, you'll need to make
  26. at least a minimal translation of the Django core.
  27. A good starting point is to copy the Django English ``.po`` file and to
  28. translate at least some :term:`translation strings <translation string>`.
  29. Message files
  30. -------------
  31. The first step is to create a :term:`message file` for a new language. A message
  32. file is a plain-text file, representing a single language, that contains all
  33. available translation strings and how they should be represented in the given
  34. language. Message files have a ``.po`` file extension.
  35. Django comes with a tool, `` makemessages``, that automates the
  36. creation and upkeep of these files.
  37. .. admonition:: A note to Django veterans
  38. The old tool ``bin/`` has been moved to the command
  39. `` makemessages`` to provide consistency throughout Django.
  40. .. admonition:: Gettext utilities
  41. The ``makemessages`` command (and ``compilemessages`` discussed later) use
  42. commands from the GNU gettext toolset: ``xgettext``, ``msgfmt``,
  43. ``msgmerge`` and ``msguniq``.
  44. .. versionchanged:: 1.2
  45. The minimum version of the ``gettext`` utilities supported is 0.15.
  46. To create or update a message file, run this command::
  47. makemessages -l de
  48. ...where ``de`` is the language code for the message file you want to create.
  49. The language code, in this case, is in :term:`locale format<locale name>`. For
  50. example, it's ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian
  51. German.
  52. The script should be run from one of two places:
  53. * The root directory of your Django project.
  54. * The root directory of your Django app.
  55. The script runs over your project source tree or your application source tree
  56. and pulls out all strings marked for translation. It creates (or updates) a
  57. message file in the directory ``locale/LANG/LC_MESSAGES``. In the ``de``
  58. example, the file will be ``locale/de/LC_MESSAGES/django.po``.
  59. By default `` makemessages`` examines every file that has the
  60. ``.html`` file extension. In case you want to override that default, use the
  61. ``--extension`` or ``-e`` option to specify the file extensions to examine::
  62. makemessages -l de -e txt
  63. Separate multiple extensions with commas and/or use ``-e`` or ``--extension``
  64. multiple times::
  65. makemessages -l de -e html,txt -e xml
  66. When :ref:`creating message files from JavaScript source code
  67. <creating-message-files-from-js-code>` you need to use the special 'djangojs'
  68. domain, **not** ``-e js``.
  69. .. admonition:: No gettext?
  70. If you don't have the ``gettext`` utilities installed, ``
  71. makemessages`` will create empty files. If that's the case, either install
  72. the ``gettext`` utilities or just copy the English message file
  73. (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting
  74. point; it's just an empty translation file.
  75. .. admonition:: Working on Windows?
  76. If you're using Windows and need to install the GNU gettext utilities so
  77. ``django-admin makemessages`` works see :ref:`gettext_on_windows` for more
  78. information.
  79. The format of ``.po`` files is straightforward. Each ``.po`` file contains a
  80. small bit of metadata, such as the translation maintainer's contact
  81. information, but the bulk of the file is a list of **messages** -- simple
  82. mappings between translation strings and the actual translated text for the
  83. particular language.
  84. For example, if your Django app contained a translation string for the text
  85. ``"Welcome to my site."``, like so::
  86. _("Welcome to my site.")
  87. ...then `` makemessages`` will have created a ``.po`` file
  88. containing the following snippet -- a message::
  89. #: path/to/python/
  90. msgid "Welcome to my site."
  91. msgstr ""
  92. A quick explanation:
  93. * ``msgid`` is the translation string, which appears in the source. Don't
  94. change it.
  95. * ``msgstr`` is where you put the language-specific translation. It starts
  96. out empty, so it's your responsibility to change it. Make sure you keep
  97. the quotes around your translation.
  98. * As a convenience, each message includes, in the form of a comment line
  99. prefixed with ``#`` and located above the ``msgid`` line, the filename and
  100. line number from which the translation string was gleaned.
  101. Long messages are a special case. There, the first string directly after the
  102. ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
  103. written over the next few lines as one string per line. Those strings are
  104. directly concatenated. Don't forget trailing spaces within the strings;
  105. otherwise, they'll be tacked together without whitespace!
  106. .. admonition:: Mind your charset
  107. When creating a PO file with your favorite text editor, first edit
  108. the charset line (search for ``"CHARSET"``) and set it to the charset
  109. you'll be using to edit the content. Due to the way the ``gettext`` tools
  110. work internally and because we want to allow non-ASCII source strings in
  111. Django's core and your applications, you **must** use UTF-8 as the encoding
  112. for your PO file. This means that everybody will be using the same
  113. encoding, which is important when Django processes the PO files.
  114. To reexamine all source code and templates for new translation strings and
  115. update all message files for **all** languages, run this::
  116. makemessages -a
  117. Compiling message files
  118. -----------------------
  119. After you create your message file -- and each time you make changes to it --
  120. you'll need to compile it into a more efficient form, for use by ``gettext``.
  121. Do this with the `` compilemessages`` utility.
  122. This tool runs over all available ``.po`` files and creates ``.mo`` files, which
  123. are binary files optimized for use by ``gettext``. In the same directory from
  124. which you ran `` makemessages``, run ``
  125. compilemessages`` like this::
  126. compilemessages
  127. That's it. Your translations are ready for use.
  128. .. admonition:: A note to Django veterans
  129. The old tool ``bin/`` has been moved to the command
  130. `` compilemessages`` to provide consistency throughout
  131. Django.
  132. .. admonition:: Working on Windows?
  133. If you're using Windows and need to install the GNU gettext utilities so
  134. ``django-admin compilemessages`` works see :ref:`gettext_on_windows` for more
  135. information.
  136. .. admonition:: .po files: Encoding and BOM usage.
  137. Django only supports ``.po`` files encoded in UTF-8 and without any BOM
  138. (Byte Order Mark) so if your text editor adds such marks to the beginning of
  139. files by default then you will need to reconfigure it.
  140. .. _creating-message-files-from-js-code:
  141. Creating message files from JavaScript source code
  142. ==================================================
  143. You create and update the message files the same way as the other Django message
  144. files -- with the `` makemessages`` tool. The only difference is
  145. you need to provide a ``-d djangojs`` parameter, like this::
  146. makemessages -d djangojs -l de
  147. This would create or update the message file for JavaScript for German.
  148. After updating message files, just run `` compilemessages``
  149. the same way as you do with normal Django message files.
  150. .. _gettext_on_windows:
  151. ``gettext`` on Windows
  152. ======================
  153. This is only needed for people who either want to extract message IDs or compile
  154. message files (``.po``). Translation work itself just involves editing existing
  155. files of this type, but if you want to create your own message files, or want to
  156. test or compile a changed message file, you will need the ``gettext`` utilities:
  157. * Download the following zip files from the GNOME servers
  158. or from one
  159. of its mirrors_
  160. * ````
  161. * ````
  162. ``X`` is the version number, we are requiring ``0.15`` or higher.
  163. * Extract the contents of the ``bin\`` directories in both files to the
  164. same folder on your system (i.e. ``C:\Program Files\gettext-utils``)
  165. * Update the system PATH:
  166. * ``Control Panel > System > Advanced > Environment Variables``.
  167. * In the ``System variables`` list, click ``Path``, click ``Edit``.
  168. * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
  169. ``Variable value`` field.
  170. .. _mirrors:
  171. You may also use ``gettext`` binaries you have obtained elsewhere, so long as
  172. the ``xgettext --version`` command works properly. Do not attempt to use Django
  173. translation utilities with a ``gettext`` package if the command ``xgettext
  174. --version`` entered at a Windows command prompt causes a popup window saying
  175. "xgettext.exe has generated errors and will be closed by Windows".
  176. .. _format-localization:
  177. Format localization
  178. ===================
  179. .. versionadded:: 1.2
  180. Django's formatting system is disabled by default. To enable it, it's
  181. necessary to set :setting:`USE_L10N = True <USE_L10N>` in your settings file.
  182. .. note::
  183. The default :file:`` file created by
  184. :djadmin:` startproject <startproject>` includes
  185. :setting:`USE_L10N = True <USE_L10N>` for convenience.
  186. When using Django's formatting system, dates and numbers on templates will be
  187. displayed using the format specified for the current locale. Two users
  188. accessing the same content, but in different language, will see date and
  189. number fields formatted in different ways, depending on the format for their
  190. current locale.
  191. Django will also use localized formats when parsing data in forms. That means
  192. Django uses different formats for different locales when guessing the format
  193. used by the user when inputting data on forms.
  194. .. note::
  195. Django uses different formats for displaying data to those it uses for
  196. parsing data. Most notably, the formats for parsing dates can't use the
  197. ``%a`` (abbreviated weekday name), ``%A`` (full weekday name),
  198. ``%b`` (abbreviated month name), ``%B`` (full month name),
  199. or ``%p`` (AM/PM).
  200. To enable a form field to localize input and output data simply use its
  201. ``localize`` argument::
  202. class CashRegisterForm(forms.Form):
  203. product = forms.CharField()
  204. revenue = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)
  205. Creating custom format files
  206. ----------------------------
  207. Django provides format definitions for many locales, but sometimes you might
  208. want to create your own, because a format files doesn't exist for your locale,
  209. or because you want to overwrite some of the values.
  210. To use custom formats, first thing to do, is to specify the path where you'll
  211. place format files. To do that, just set your :setting:`FORMAT_MODULE_PATH`
  212. setting to the path (in the format ``'``) where format files
  213. will exists.
  214. Files are not placed directly in this directory, but in a directory named as
  215. the locale, and must be named ````.
  216. To customize the English formats, a structure like this would be needed::
  217. mysite/
  218. formats/
  220. en/
  223. where :file:`` contains custom format definitions. For example::
  225. to use a space as a thousand separator, instead of the default for English,
  226. a comma.
  227. .. _topic-l10n-templates:
  228. Controlling localization in templates
  229. =====================================
  230. When you have enabled localization using :setting:`USE_L10N`, Django
  231. will try to use a locale specific format whenever it outputs a value
  232. in a template.
  233. However, it may not always be appropriate to use localized values --
  234. for example, if you're outputting Javascript or XML that is designed
  235. to be machine-readable, you will always want unlocalized values. You
  236. may also want to use localization in selected templates, rather than
  237. using localization everywhere.
  238. To allow for fine control over the use of localization, Django
  239. provides the ``l10n`` template library that contains the following
  240. tags and filters.
  241. Template tags
  242. -------------
  243. .. templatetag:: localize
  244. localize
  245. ~~~~~~~~
  246. .. versionadded:: 1.3
  247. Enables or disables localization of template variables in the
  248. contained block.
  249. This tag allows a more fine grained control of localization than
  250. :setting:`USE_L10N`.
  251. To activate or deactivate localization for a template block, use::
  252. {% localize on %}
  253. {{ value }}
  254. {% endlocalize %}
  255. {% localize off %}
  256. {{ value }}
  257. {% endlocalize %}
  258. .. note::
  259. The value of :setting:`USE_L10N` is not respected inside of a
  260. `{% localize %}` block.
  261. See :tfilter:`localized` and :tfilter:`unlocalized` for a template filter that will
  262. do the same job on a per-variable basis.
  263. Template filters
  264. ----------------
  265. .. templatefilter:: localize
  266. localize
  267. ~~~~~~~~
  268. .. versionadded:: 1.3
  269. Forces localization of a single value.
  270. For example::
  271. {{ value|localize }}
  272. To disable localization on a single value, use :tfilter:`unlocalize`. To control
  273. localization over a large section of a template, use the :ttag:`localize` template
  274. tag.
  275. .. templatefilter:: unlocalize
  276. unlocalize
  277. ~~~~~~~~~~
  278. .. versionadded:: 1.3
  279. Forces a single value to be printed without localization.
  280. For example::
  281. {{ value|unlocalize }}
  282. To force localization of a single value, use :tfilter:`localize`. To
  283. control localization over a large section of a template, use the
  284. :ttag:`localize` template tag.