Django

Code

root/django/branches/0.90-bugfixes/docs/i18n.txt

Revision 1209, 23.2 kB (checked in by adrian, 3 years ago)

Grammar cleanups for recent documentation and docstring changes.

Line 
1 ====================
2 Internationalization
3 ====================
4
5 Django has full support for internationalization of text in code and templates.
6 Here's how it works.
7
8 Overview
9 ========
10
11 The goal of internationalization is to allow a single Web application to offer
12 its content and functionality in multiple languages.
13
14 You, the Django developer, can accomplish this goal by adding a minimal amount
15 of hooks to your Python code and templates. These hooks are called
16 **translation strings**. They tell Django: "This text should be translated into
17 the end user's language, if a translation for this text is available in that
18 language."
19
20 Django takes care of using these hooks to translate Web apps, on the fly,
21 according to users' language preferences.
22
23 Essentially, Django does two things:
24
25     * It lets developers and template authors specify which parts of their apps
26       should be translatable.
27     * It uses these hooks to translate Web apps for particular users according
28       to their language preferences.
29
30 How to internationalize your app: in three steps
31 ------------------------------------------------
32
33     1. Embed translation strings in your Python code and templates.
34     2. Get translations for those strings, in whichever languages you want to
35        support.
36     3. Activate the locale middleware in your Django settings.
37
38
39 .. admonition:: Behind the scenes
40
41     Django's translation machinery uses the standard ``gettext`` module that
42     comes with Python.
43
44 How to specify translation strings
45 ==================================
46
47 Translation strings specify "This text should be translated." These strings can
48 appear in your Python code and templates. It's your responsibility to mark
49 translatable strings; the system can only translate strings it knows about.
50
51 In Python code
52 --------------
53
54 Standard translation
55 ~~~~~~~~~~~~~~~~~~~~
56
57 Specify a translation string by using the function ``_()``. (Yes, the name of
58 the function is the "underscore" character.) This function is available
59 globally in any Python module; you don't have to import it.
60
61 In this example, the text ``"Welcome to my site."`` is marked as a translation
62 string::
63
64     def my_view(request):
65         output = _("Welcome to my site.")
66         return HttpResponse(output)
67
68 The function ``django.utils.translation.gettext()`` is identical to ``_()``.
69 This example is identical to the previous one::
70
71     from django.utils.translation import gettext
72     def my_view(request):
73         output = gettext("Welcome to my site.")
74         return HttpResponse(output)
75
76 Translation works on computed values. This example is identical to the previous
77 two::
78
79     def my_view(request):
80         words = ['Welcome', 'to', 'my', 'site.']
81         output = _(' '.join(words))
82         return HttpResponse(output)
83
84 Translation works on variables. Again, here's an identical example::
85
86     def my_view(request):
87         sentence = 'Welcome to my site.'
88         output = _(sentence)
89         return HttpResponse(output)
90
91 (The caveat with using variables or computed values, as in the previous two
92 examples, is that Django's translation-string-detecting utility,
93 ``make-messages.py``, won't be able to find these strings. More on
94 ``make-messages`` later.)
95
96 The strings you pass to ``_()`` or ``gettext()`` can take placeholders,
97 specified with Python's standard named-string interpolation syntax. Example::
98
99     def my_view(request, n):
100         output = _('%(name)s is my name.') % {'name': n}
101         return HttpResponse(output)
102
103 This technique lets language-specific translations reorder the placeholder
104 text. For example, an English translation may be ``"Adrian is my name."``,
105 while a Spanish translation may be ``"Me llamo Adrian."`` -- with the
106 placeholder (the name) placed after the translated text instead of before it.
107
108 For this reason, you should use named-string interpolation (e.g., ``%(name)s``)
109 instead of positional interpolation (e.g., ``%s`` or ``%d``). If you used
110 positional interpolation, translations wouldn't be able to reorder placeholder
111 text.
112
113 Marking strings as no-op
114 ~~~~~~~~~~~~~~~~~~~~~~~~
115
116 Use the function ``django.utils.translation.gettext_noop()`` to mark a string
117 as a translation string without translating it. The string is later translated
118 from a variable.
119
120 Use this if you have constant strings that should be stored in the source
121 language because they are exchanged over systems or users -- such as strings in
122 a database -- but should be translated at the last possible point in time, such
123 as when the string is presented to the user.
124
125 Lazy translation
126 ~~~~~~~~~~~~~~~~
127
128 Use the function ``django.utils.translation.gettext_lazy()`` to translate
129 strings lazily -- when the value is accessed rather than when the
130 ``gettext_lazy()`` function is called.
131
132 For example, to translate a model's ``help_text``, do the following::
133
134     from django.utils.translation import gettext_lazy
135
136     class MyThing(meta.Model):
137         name = meta.CharField(help_text=gettext_lazy('This is the help text'))
138
139 In this example, ``gettext_lazy()`` stores a lazy reference to the string --
140 not the actual translation. The translation itself will be done when the string
141 is used in a string context, such as template rendering on the Django admin site.
142
143 If you don't like the verbose name ``gettext_lazy``, you can just alias it as
144 ``_`` (underscore), like so::
145
146     from django.utils.translation import gettext_lazy as _
147
148     class MyThing(meta.Model):
149         name = meta.CharField(help_text=_('This is the help text'))
150
151 Always use lazy translations in `Django models`_. And it's a good idea to add
152 translations for the field names and table names, too. This means writing
153 explicit ``verbose_name`` and ``verbose_name_plural`` options in the ``META``
154 class, though::
155
156     from django.utils.translation import gettext_lazy as _
157
158     class MyThing(meta.Model):
159         name = meta.CharField(_('name'), help_text=_('This is the help text'))
160         class META:
161             verbose_name = _('my thing')
162             verbose_name_plural = _('mythings')
163
164 .. _Django models: http://www.djangoproject.com/documentation/model_api/
165
166 Pluralization
167 ~~~~~~~~~~~~~
168
169 Use the function ``django.utils.translation.ngettext()`` to specify pluralized
170 messages. Example::
171
172     from django.utils.translation import ngettext
173     def hello_world(request, count):
174         page = ngettext('there is %(count)d object', 'there are %(count)d objects', count) % {
175             'count': count,
176         }
177         return HttpResponse(page)
178
179 ``ngettext`` takes three arguments: the singular translation string, the plural
180 translation string and the number of objects (which is passed to the
181 translation languages as the ``count`` variable).
182
183 In template code
184 ----------------
185
186 Using translations in `Django templates`_ uses two template tags and a slightly
187 different syntax than in Python code. To give your template access to these
188 tags, put ``{% load i18n %}`` toward the top of your template.
189
190 The ``{% trans %}`` template tag translates a constant string or a variable
191 content::
192
193     <title>{% trans "This is the title." %}</title>
194
195 If you only want to mark a value for translation, but translate it later from a
196 variable, use the ``noop`` option::
197
198     <title>{% trans "value" noop %}</title>
199
200 It's not possible to use template variables in ``{% trans %}`` -- only constant
201 strings, in single or double quotes, are allowed. If your translations require
202 variables (placeholders), use ``{% blocktrans %}``. Example::
203
204     {% blocktrans %}This will have {{ value }} inside.{% endblocktrans %}
205
206 To translate a template expression -- say, using template filters -- you need
207 to bind the expression to a local variable for use within the translation
208 block::
209
210     {% blocktrans with value|filter as myvar %}
211     This will have {{ myvar }} inside.
212     {% endblocktrans %}
213
214 To pluralize, specify both the singular and plural forms with the
215 ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
216 ``{% endblocktrans %}``. Example::
217
218     {% blocktrans count list|counted as counter %}
219     There is only one {{ name }} object.
220     {% plural %}
221     There are {{ counter }} {{ name }} objects.
222     {% endblocktrans %}
223
224 Internally, all block and inline translations use the appropriate
225 ``gettext`` / ``ngettext`` call.
226
227 Each ``DjangoContext`` has access to two translation-specific variables:
228
229     * ``LANGUAGES`` is a list of tuples in which the first element is the
230       language code and the second is the language name (in that language).
231     * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
232       Example: ``en-us``. (See "How language preference is discovered", below.)
233
234 If you don't use the ``DjangoContext`` extension, you can get those values with
235 two tags::
236
237     {% get_current_language as LANGUAGE_CODE %}
238     {% get_available_languages as LANGUAGES %}
239
240 These tags also require a ``{% load i18n %}``.
241
242 Translation hooks are also available within any template block tag that accepts
243 constant strings. In those cases, just use ``_()`` syntax to specify a
244 translation string. Example::
245
246     {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
247
248 In this case, both the tag and the filter will see the already-translated
249 string, so they don't need to be aware of translations.
250
251 .. _Django templates: http://www.djangoproject.com/documentation/templates_python/
252
253 How to create language files
254 ============================
255
256 Once you've tagged your strings for later translation, you need to write (or
257 obtain) the language translations themselves. Here's how that works.
258
259 Message files
260 -------------
261
262 The first step is to create a **message file** for a new language. A message
263 file is a plain-text file, representing a single language, that contains all
264 available translation strings and how they should be represented in the given
265 language. Message files have a ``.po`` file extension.
266
267 Django comes with a tool, ``bin/make-messages.py``, that automates the creation
268 and upkeep of these files.
269
270 To create or update a message file, run this command::
271
272     bin/make-messages.py -l de
273
274 ...where ``de`` is the language code for the message file you want to create.
275 The language code, in this case, is in locale format. For example, it's
276 ``pt_BR`` for Brazilian and ``de_AT`` for Austrian German.
277
278 The script should be run from one of three places:
279
280     * The root ``django`` directory (not a Subversion checkout, but the one
281       that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
282       path).
283     * The root directory of your Django project.
284     * The root directory of your Django app.
285
286 The script runs over the entire Django source tree and pulls out all strings
287 marked for translation. It creates (or updates) a message file in the directory
288 ``conf/locale``. In the ``de`` example, the file will be
289 ``conf/locale/de/LC_MESSAGES/django.po``.
290
291 .. admonition:: No gettext?
292
293     If you don't have the ``gettext`` utilities installed, ``make-messages.py``
294     will create empty files. If that's the case, either install the ``gettext``
295     utilities or just copy the English message file
296     (``conf/locale/en/LC_MESSAGES/django.po``) and use it as a starting point;
297     it's just an empty translation file.
298
299 The format of ``.po`` files is straightforward. Each ``.po`` file contains a
300 small bit of metadata, such as the translation maintainer's contact
301 information, but the bulk of the file is a list of **messages** -- simple
302 mappings between translation strings and the actual translated text for the
303 particular language.
304
305 For example, if your Django app contained a translation string for the text
306 ``"Welcome to my site."``, like so::
307
308     _("Welcome to my site.")
309
310 ...then ``make-messages.py`` will have created a ``.po`` file containing the
311 following snippet -- a message::
312
313     #: path/to/python/module.py:23
314     msgid "Welcome to my site."
315     msgstr ""
316
317 A quick explanation:
318
319     * ``msgid`` is the translation string, which appears in the source. Don't
320       change it.
321     * ``msgstr`` is where you put the language-specific translation. It starts
322       out empty, so it's your responsibility to change it. Make sure you keep
323       the quotes around your translation.
324     * As a convenience, each message includes the filename and line number
325       from which the translation string was gleaned.
326
327 Long messages are a special case. There, the first string directly after the
328 ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
329 written over the next few lines as one string per line. Those strings are
330 directlyconcatenated. Don't forget trailing spaces within the strings;
331 otherwise, they'll be tacked together without whitespace!
332
333 .. admonition:: Mind your charset
334
335     When creating a ``.po`` file with your favorite text editor, first edit
336     the charset line (search for ``"CHARSET"``) and set it to the charset
337     you'll be using to edit the content. Generally, utf-8 should work for most
338     languages, but ``gettext`` should handle any charset you throw at it.
339
340 To reexamine all source code and templates for new translation strings and
341 update all message files for **all** languages, run this::
342
343     make-messages.py -a
344
345 Compiling message files
346 -----------------------
347
348 After you create your message file -- and each time you make changes to it --
349 you'll need to compile it into a more efficient form, for use by ``gettext``.
350 Do this with the ``bin/compile-messages.py`` utility.
351
352 This tool runs over all available ``.po`` files and creates ``.mo`` files,
353 which are binary files optimized for use by ``gettext``. In the same directory
354 from which you ran ``make-messages.py``, run ``compile-messages.py`` like
355 this::
356
357    bin/compile-messages.py
358
359 That's it. Your translations are ready for use.
360
361 .. admonition:: A note to translators
362
363     If you've created a translation in a language Django doesn't yet support,
364     please let us know! We'll add it to the global list of available languages
365     in the global Django settings (``settings.LANGUAGES``).
366
367 How Django discovers language preference
368 ========================================
369
370 Once you've prepared your translations -- or, if you just want to use the
371 translations that come with Django -- you'll just need to activate translation
372 for your app.
373
374 Behind the scenes, Django has a very flexible model of deciding which language
375 should be used -- installation-wide, for a particular user, or both.
376
377 To set an installation-wide language preference, set ``LANGUAGE_CODE`` in your
378 `settings file`_. Django uses this language as the default translation -- the
379 final attempt if no other translator finds a translation.
380
381 If all you want to do is run Django with your native language, and a language
382 file is available for your language, all you need to do is set
383 ``LANGUAGE_CODE``.
384
385 If you want to let each individual user specify which language he or she
386 prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
387 selection based on data from the request. It customizes content for each user.
388
389 To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
390 to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
391 should follow these guidelines:
392
393     * Make sure it's one of the first middlewares installed.
394     * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
395       makes use of session data.
396     * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
397
398 For example, your ``MIDDLEWARE_CLASSES`` might look like this::
399
400     MIDDLEWARE_CLASSES = (
401        'django.middleware.sessions.SessionMiddleware',
402        'django.middleware.locale.LocaleMiddleware',
403        'django.middleware.common.CommonMiddleware',
404     )
405
406 (For more on middleware, see the `middleware documentation`_.)
407
408 ``LocaleMiddleware`` tries to determine the user's language preference by
409 following this algorithm:
410
411     * First, it looks for a ``django_language`` key in the the current user's
412       `session`_.
413     * Failing that, it looks for a cookie called ``django_language``.
414     * Failing that, it looks at the ``Accept-Language`` HTTP header. This
415       header is sent by your browser and tells the server which language(s) you
416       prefer, in order by priority. Django tries each language in the header
417       until it finds one with available translations.
418     * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
419
420 Notes:
421
422     * In each of these places, the language preference is expected to be in the
423       standard language format, as a string. For example, Brazilian is
424       ``pt-br``.
425     * If a base language is available but the sublanguage specified is not,
426       Django uses the base language. For example, if a user specifies ``de-at``
427       (Austrian German) but Django only has ``de`` available, Django uses
428       ``de``.
429     * Only languages listed in the `LANGUAGES setting`_ can be selected. If
430       you want to restrict the language selection to a subset of provided
431       languages (because your appliaction doesn't provide all those languages),
432       set ``LANGUAGES`` to a list of languages. For example::
433
434           LANGUAGES = (
435             ('de', _('German')),
436             ('en', _('English')),
437           )
438
439       This example restricts languages that are available for automatic
440       selection to German and English (and any sublanguage, like de-ch or
441       en-us).
442
443       .. _LANGUAGES setting: http://www.djangoproject.com/documentation/settings/#languages
444
445 Once ``LocaleMiddleware`` determines the user's preference, it makes this
446 preference available as ``request.LANGUAGE_CODE`` for each `request object`_.
447 Feel free to read this value in your view code. Here's a simple example::
448
449     def hello_world(request, count):
450         if request.LANGUAGE_CODE == 'de-at':
451             return HttpResponse("You prefer to read Austrian German.")
452         else:
453             return HttpResponse("You prefer to read another language.")
454
455 Note that, with static (middleware-less) translation, the language is in
456 ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
457 in ``request.LANGUAGE_CODE``.
458
459 .. _settings file: http://www.djangoproject.com/documentation/settings/
460 .. _middleware documentation: http://www.djangoproject.com/documentation/middleware/
461 .. _session: http://www.djangoproject.com/documentation/sessions/
462 .. _request object: http://www.djangoproject.com/documentation/request_response/#httprequest-objects
463
464 The ``set_language`` redirect view
465 ==================================
466
467 As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
468 that sets a user's language preference and redirects back to the previous page.
469
470 Activate this view by adding the following line to your URLconf::
471
472     (r'^i18n/', include('django.conf.urls.i18n')),
473
474 (Note that this example makes the view available at ``/i18n/setlang/``.)
475
476 The view expects to be called via the ``GET`` method, with a ``language``
477 parameter set in the query string. If session support is enabled, the view
478 saves the language choice in the user's session. Otherwise, it saves the
479 language choice in a ``django_language`` cookie.
480
481 After setting the language choice, Django redirects the user, following this
482 algorithm:
483
484     * Django looks for a ``next`` parameter in the query string.
485     * If that doesn't exist, or is empty, Django tries the URL in the
486       ``Referer`` header.
487     * If that's empty -- say, if a user's browser suppresses that header --
488       then the user will be redirected to ``/`` (the site root) as a fallback.
489
490 Here's example HTML template code::
491
492     <form action="/i18n/setlang/" method="get">
493     <input name="next" type="hidden" value="/next/page/" />
494     <select name="language">
495     {% for lang in LANGUAGES %}
496     <option value="{{ lang.0 }}">{{ lang.1 }}</option>
497     {% endfor %}
498     </select>
499     <input type="submit" value="Go" />
500     </form>
501
502 Using translations in your own projects
503 =======================================
504
505 Django looks for translations by following this algorithm:
506
507     * First, it looks for a ``locale`` directory in the application directory
508       of the view that's being called. If it finds a translation for the
509       selected language, the translation will be installed.
510     * Next, it looks for a ``locale`` directory in the project directory. If it
511       finds a translation, the translation will be installed.
512     * Finally, it checks the base translation in ``django/conf/locale``.
513
514 This way, you can write applications that include their own translations, and
515 you can override base translations in your project path. Or, you can just build
516 a big project out of several apps and put all translations into one big project
517 message file. The choice is yours.
518
519 All message file repositories are structured the same way. They are:
520
521     * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
522     * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
523     * All paths listed in ``LOCALE_PATHS`` in your settings file are
524       searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
525     * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
526
527 To create message files, you use the same ``make-messages.py`` tool as with the
528 Django message files. You only need to be in the right place -- in the directory
529 where either the ``conf/locale`` (in case of the source tree) or the ``locale/``
530 (in case of app messages or project messages) directory are located. And you
531 use the same ``compile-messages.py`` to produce the binary ``django.mo`` files that
532 are used by ``gettext``.
533
534 Application message files are a bit complicated to discover -- they need the
535 ``LocaleMiddleware``. If you don't use the middleware, only the Django message
536 files and project message files will be processed.
537
538 Finally, you should give some thought to the structure of your translation
539 files. If your applications need to be delivered to other users and will
540 be used in other projects, you might want to use app-specific translations.
541 But using app-specific translations and project translations could produce
542 weird problems with ``make-messages``: ``make-messages`` will traverse all
543 directories below the current path and so might put message IDs into the
544 project message file that are already in application message files.
545
546 The easiest way out is to store applications that are not part of the project
547 (and so carry their own translations) outside the project tree. That way,
548 ``make-messages`` on the project level will only translate strings that are
549 connected to your explicit project and not strings that are distributed
550 independently.
551
552 Specialities of Django translation
553 ==================================
554
555 If you know ``gettext``, you might note these specialities in the way Django
556 does translation:
557
558     * The string domain is always ``django``. The string domain is used to
559       differentiate between different programs that store their data in a
560       common message-file library (usually ``/usr/share/locale/``). In Django's
561       case, there are Django-specific locale libraries, so the domain itself
562       isn't used. We could store app message files with different names and put
563       them, say, in the project library, but we decided against this. With
564       message files in the application tree, apps can be distributed more
565       easily.
566     * Django only uses ``gettext`` and ``gettext_noop``. That's because Django
567       always uses ``DEFAULT_CHARSET`` strings internally. There isn't much use
568       in using ``ugettext``, because you'll always need to produce utf-8
569       anyway.
570     * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
571       ``xgettext`` and ``msgfmt``. That's mostly for convenience.
Note: See TracBrowser for help on using the browser.