README.rst 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. Tools for using Babel with Django
  2. =================================
  3. This package contains various utilities for integration of `Babel`_ into the
  4. `Django`_ web framework:
  5. * A message extraction plugin for Django templates.
  6. * A middleware class that adds the Babel `Locale`_ object to requests.
  7. * A set of template tags for date and number formatting.
  8. Extracting Messages
  9. -------------------
  10. Babel provides a message extraction framework similar to GNU ``xgettext``, but
  11. more extensible and geared towards Python applications. While Django does
  12. provide `wrapper scripts`_ for making the use of ``xgettext`` more
  13. convenient, the extraction functionality is rather limited. For example, you
  14. can't use template files with an extension other than ``.html``, and everything
  15. needs to be in your project package directory.
  16. Extraction Method Mapping
  17. ^^^^^^^^^^^^^^^^^^^^^^^^^
  18. So django-babel comes with an extraction method plugin that can extract
  19. localizable messages from Django template files. Python is supported out of the
  20. box by Babel. To use this extraction functionality, create a file called
  21. ``babel.cfg`` in your project directory (the directory above your project
  22. package), with the content:
  23. .. code-block:: ini
  24. [django: templates/**.*]
  25. [django: mypkg/*/templates/**.*]
  26. [python: mypkg/**.py]
  27. This instructs Babel to look for any files in the top-level ``templates``
  28. directory, or any files in application ``templates`` directories, and use the
  29. extraction method named “django” to extract messages from those template files.
  30. You'll need to adjust those glob patterns to wherever you my be storing your
  31. templates.
  32. Also, any files with the extension ``.py`` inside your package directory (replace
  33. “mypkg” with the actual name of your Django project package) are processed by
  34. the “python” extraction method.
  35. If you don't use setuptools, or for some reason haven't installed django-babel
  36. using setuptools/pip, you'll need to define what function the extraction method
  37. “django” maps to. This is done in an extra section at the top of the
  38. configuration file:
  39. .. code-block:: ini
  40. [extractors]
  41. django = django_babel.extract:extract_django
  42. The encoding of the templates is assumed to be UTF-8. If you are using a
  43. different encoding, you will need to specify it in the configuration. For
  44. example:
  45. .. code-block:: ini
  46. [django: templates/**.*]
  47. encoding = iso-8859-1
  48. Running the Extraction Process
  49. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  50. Once you've set up the configuration file, the actual extraction is performed
  51. by executing the command-line program ``pybabel`` which is installed alongside
  52. the Babel package:
  53. .. code-block:: bash
  54. $ cd projectdir
  55. $ pybabel extract -F babel.cfg -o mypkg/locale/django.pot .
  56. This creates the PO file template in ``mypkg/locale/django.pot``.
  57. Creating and Updating Translations Catalogs
  58. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  59. If you don't already have translation catalogs, you need to create them. This
  60. is done using the ``pybabel init`` command:
  61. .. code-block:: bash
  62. $ pybabel init -D django -i mypkg/locale/django.pot -d mypkg/locale -l en_US
  63. $ pybabel init -D django -i mypkg/locale/django.pot -d mypkg/locale -l de_DE
  64. This should create two files: ``mypkg/locale/en_US/django.po`` and
  65. ``mypkg/locale/de_DE/django.po``. These files are where you put the actual
  66. translations.
  67. When you modify your Python source files or your templates, you genereally need
  68. to sync the translation catalogs. For that, you first perform a fresh
  69. extraction as described in the previous section, so that the ``django.pot`` file
  70. gets updated.
  71. Then, you run the ``pybabel update`` command to merge the changes into the
  72. translation catalogs:
  73. ```bash
  74. $ pybabel update -D django -i mypkg/locale/django.pot -d mypkg/locale
  75. ```
  76. This will update all the ``.po`` files found in the ``mypkg/locale`` directory.
  77. Compiling Translations Catalogs
  78. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  79. Finally, you need to compile those ``.po`` files to binary ``.mo`` files. Use the
  80. `pybabel compile` command for that:
  81. .. code-block:: bash
  82. $ pybabel compile -D django -d mypkg/locale
  83. Add the ``--statistics`` option to get information about the completeness of your
  84. translations:
  85. .. code-block:: bash
  86. $ pybabel compile -D django -d mypkg/locale --statistics
  87. Using ``setup.py``
  88. ^^^^^^^^^^^^^^^^^^
  89. Much of the above process can be automated if you add a ``setup.py`` script to
  90. your project and use the distutils/setuptools commands that come with Babel.
  91. This is described at `Distutils/Setuptools Integration`_.
  92. Using the Middleware
  93. --------------------
  94. To use the Babel middleware, add it to the list of ``MIDDLEWARE_CLASSES`` in your
  95. settings module. If you're also using Django's own ``LocaleMiddleware`` to vary
  96. the locale based on user preference, the Babel middleware must be inserted
  97. after the Django one:
  98. .. code-block:: python
  99. MIDDLEWARE_CLASSES = (
  100. ...
  101. 'django.middleware.locale.LocaleMiddleware',
  102. 'django_babel.middleware.LocaleMiddleware',
  103. ...
  104. )
  105. This adds a ``locale`` attribute to the request object, which is an instance of
  106. the Babel ``Locale`` class. You can access the locale via ``request.locale`` when
  107. the request object is available, or otherwise use the
  108. ``django_babel.middleware.get_current_locale()`` function to get the current
  109. locale from a thread-local cache.
  110. Using the Template Tags
  111. -----------------------
  112. The template filters provided by django-babel allow formatting of date/time and
  113. number values in a locale-sensitive manner, providing much more powerful
  114. alternatives to the ``date``, ``time``, and ``floatformat`` filters that come with
  115. Django.
  116. To make the template filters/tags available, you need to add django-babel to
  117. the list of ``INSTALLED_APPS`` in your settings module:
  118. .. code-block:: python
  119. INSTALLED_APPS = (
  120. ...
  121. 'django_babel',
  122. ...
  123. )
  124. And in every template you want to use the filters, you need to explicitly load
  125. the django-babel library:
  126. .. code-block:: django
  127. {% load babel %}
  128. General information on date/time and number formatting can be found at
  129. `Date Formatting`_ and `Number Formatting`_.
  130. The following filters are made available. The examples assume a locale of
  131. ``en_US``.
  132. ``datefmt``
  133. ^^^^^^^^^^^
  134. Renders a string representation of a date.
  135. * **Input**: ``datetime.date``, ``datetime.datetime``, or a float/int timestamp
  136. * **Parameters**: the format name or pattern (optional)
  137. Assuming that ``book.pubdate`` returns a ``datetime.date`` or
  138. ``datetime.datetime`` object:
  139. .. code-block:: django
  140. {{ book.pubdate|datefmt:"short" }}
  141. would render: **4/1/07**, and
  142. .. code-block:: django
  143. {{ book.pubdate|datefmt:"E, MMM dd yyyy GGG" }}
  144. would render: **Sun, Apr 01 2007 AD**
  145. ``datetimefmt``
  146. ^^^^^^^^^^^^^^^
  147. Renders a string representation of a date and time.
  148. * **Input**: ``datetime.datetime``, or a float/int timestamp
  149. * **Parameters**: the format name or pattern (optional)
  150. Examples:
  151. .. code-block:: django
  152. {{ book.pubdate|datetimefmt:"short" }}
  153. would render: **4/1/07 3:30 PM**, and
  154. .. code-block:: django
  155. {{ book.pubdate|datetimefmt:"E, MMM dd yyyy GGG' - 'HH:mm:ss'" }}
  156. would render: **Sun, Apr 01 2007 AD - 15:30:00**
  157. ``timefmt``
  158. ^^^^^^^^^^^
  159. Renders a string representation of a time.
  160. * **Input**: ``datetime.datetime``, ``datetime.time``, or a float/int timestamp
  161. * **Parameters**: the format name or pattern (optional)
  162. Examples:
  163. .. code-block:: django
  164. {{ book.pubdate|timefmt:"short" }}
  165. would render: **3:30 PM**, and
  166. .. code-block:: django
  167. {{ book.pubdate|timefmt:"h 'o''clock' a'" }}
  168. would render: **3 o'clock PM**
  169. ``decimalfmt``
  170. ^^^^^^^^^^^^^^
  171. Renders a string representation of a decimal number.
  172. * **Input**: a `Decimal` object, or a float/int/long value
  173. * **Parameters**: the format name or pattern (optional)
  174. Examples:
  175. .. code-block:: django
  176. {{ book.pagecount|decimalfmt }}
  177. would render: **1,234**, and
  178. .. code-block:: django
  179. {{ book.pagecount|decimalfmt:"#,##0.00" }}
  180. would render: **1,234.00**
  181. ``currencyfmt``
  182. ^^^^^^^^^^^^^^^
  183. Renders a number formatted as a currency value.
  184. * **Input**: a ``Decimal`` object, or a float/int/long value
  185. * **Parameters**: the currency code
  186. Examples:
  187. .. code-block:: django
  188. {{ book.price|currencyfmt:"USD" }}
  189. would render: **$49.90**
  190. ``percentfmt``
  191. ^^^^^^^^^^^^^^
  192. Renders a string representation of a number as a percentage.
  193. * **Input**: a ``Decimal`` object, or a float/int/long value
  194. * **Parameters**: the format name or pattern (optional)
  195. Examples:
  196. Assuming ``book.rebate`` would return ``0.15``,
  197. .. code-block:: django
  198. {{ book.rebate|percentfmt }}
  199. would render **15%**, and
  200. .. code-block:: django
  201. {{ book.rebate|percentfmt:"#,##0.00%" }}
  202. would render **15.00%**.
  203. ``scientificfmt``
  204. ^^^^^^^^^^^^^^^^^
  205. Renders a string representation of a number using scientific notation.
  206. * **Input**: a ``Decimal`` object, or a float/int/long value
  207. * **Parameters**: none
  208. Examples:
  209. Assuming ``book.numsold`` would return 1.000.000,
  210. .. code-block:: django
  211. {{ book.numsold|scientificfmt }}
  212. would render **10E5**.
  213. .. _Babel: http://babel.pocoo.org/
  214. .. _Django: https://www.djangoproject.com/
  215. .. _wrapper scripts: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#localization-how-to-create-language-files
  216. .. _Distutils/Setuptools Integration: http://babel.pocoo.org/en/stable/setup.html
  217. .. _Date Formatting: http://babel.pocoo.org/en/stable/dates.html
  218. .. _Number Formatting: http://babel.pocoo.org/en/stable/numbers.html
  219. .. _Locale: http://babel.pocoo.org/en/stable/api/core.html#babel.core.Locale