PageRenderTime 101ms CodeModel.GetById 90ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/i18n/localization.txt

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