Django

Code

root/django/branches/gis/docs/i18n.txt

Revision 8215, 38.7 kB (checked in by jbronn, 4 months ago)

gis: Merged revisions 7981-8001,8003-8011,8013-8033,8035-8036,8038-8039,8041-8063,8065-8076,8078-8139,8141-8154,8156-8214 via svnmerge from trunk.

  • Property svn:eol-style set to native
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 If you don't need internationalization in your app
31 ==================================================
32
33 Django's internationalization hooks are on by default, and that means there's a
34 bit of i18n-related overhead in certain places of the framework. If you don't
35 use internationalization, you should take the two seconds to set
36 ``USE_I18N = False`` in your settings file. If ``USE_I18N`` is set to
37 ``False``, then Django will make some optimizations so as not to load the
38 internationalization machinery. See the `documentation for USE_I18N`_.
39
40 You'll probably also want to remove ``'django.core.context_processors.i18n'``
41 from your ``TEMPLATE_CONTEXT_PROCESSORS`` setting.
42
43 .. _documentation for USE_I18N: ../settings/#use-i18n
44
45 If you do need internationalization: three steps
46 ================================================
47
48     1. Embed translation strings in your Python code and templates.
49     2. Get translations for those strings, in whichever languages you want to
50        support.
51     3. Activate the locale middleware in your Django settings.
52
53 .. admonition:: Behind the scenes
54
55     Django's translation machinery uses the standard ``gettext`` module that
56     comes with Python.
57
58 1. How to specify translation strings
59 =====================================
60
61 Translation strings specify "This text should be translated." These strings can
62 appear in your Python code and templates. It's your responsibility to mark
63 translatable strings; the system can only translate strings it knows about.
64
65 In Python code
66 --------------
67
68 Standard translation
69 ~~~~~~~~~~~~~~~~~~~~
70
71 Specify a translation string by using the function ``ugettext()``. It's
72 convention to import this as a shorter alias, ``_``, to save typing.
73
74 .. note::
75     Python's standard library ``gettext`` module installs ``_()`` into the
76     global namespace, as an alias for ``gettext()``. In Django, we have chosen
77     not to follow this practice, for a couple of reasons:
78
79       1. For international character set (Unicode) support, ``ugettext()`` is
80          more useful than ``gettext()``. Sometimes, you should be using
81          ``ugettext_lazy()`` as the default translation method for a particular
82          file. Without ``_()`` in the global namespace, the developer has to
83          think about which is the most appropriate translation function.
84
85       2. The underscore character (``_``) is used to represent "the previous
86          result" in Python's interactive shell and doctest tests. Installing a
87          global ``_()`` function causes interference. Explicitly importing
88          ``ugettext()`` as ``_()`` avoids this problem.
89
90 In this example, the text ``"Welcome to my site."`` is marked as a translation
91 string::
92
93     from django.utils.translation import ugettext as _
94
95     def my_view(request):
96         output = _("Welcome to my site.")
97         return HttpResponse(output)
98
99 Obviously, you could code this without using the alias. This example is
100 identical to the previous one::
101
102     from django.utils.translation import ugettext
103
104     def my_view(request):
105         output = ugettext("Welcome to my site.")
106         return HttpResponse(output)
107
108 Translation works on computed values. This example is identical to the previous
109 two::
110
111     def my_view(request):
112         words = ['Welcome', 'to', 'my', 'site.']
113         output = _(' '.join(words))
114         return HttpResponse(output)
115
116 Translation works on variables. Again, here's an identical example::
117
118     def my_view(request):
119         sentence = 'Welcome to my site.'
120         output = _(sentence)
121         return HttpResponse(output)
122
123 (The caveat with using variables or computed values, as in the previous two
124 examples, is that Django's translation-string-detecting utility,
125 ``django-admin.py makemessages``, won't be able to find these strings. More on
126 ``makemessages`` later.)
127
128 The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
129 specified with Python's standard named-string interpolation syntax. Example::
130
131     def my_view(request, n):
132         output = _('%(name)s is my name.') % {'name': n}
133         return HttpResponse(output)
134
135 This technique lets language-specific translations reorder the placeholder
136 text. For example, an English translation may be ``"Adrian is my name."``,
137 while a Spanish translation may be ``"Me llamo Adrian."`` -- with the
138 placeholder (the name) placed after the translated text instead of before it.
139
140 For this reason, you should use named-string interpolation (e.g., ``%(name)s``)
141 instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
142 have more than a single parameter. If you used positional interpolation,
143 translations wouldn't be able to reorder placeholder text.
144
145 Marking strings as no-op
146 ~~~~~~~~~~~~~~~~~~~~~~~~
147
148 Use the function ``django.utils.translation.ugettext_noop()`` to mark a string
149 as a translation string without translating it. The string is later translated
150 from a variable.
151
152 Use this if you have constant strings that should be stored in the source
153 language because they are exchanged over systems or users -- such as strings in
154 a database -- but should be translated at the last possible point in time, such
155 as when the string is presented to the user.
156
157 Lazy translation
158 ~~~~~~~~~~~~~~~~
159
160 Use the function ``django.utils.translation.ugettext_lazy()`` to translate
161 strings lazily -- when the value is accessed rather than when the
162 ``ugettext_lazy()`` function is called.
163
164 For example, to translate a model's ``help_text``, do the following::
165
166     from django.utils.translation import ugettext_lazy
167
168     class MyThing(models.Model):
169         name = models.CharField(help_text=ugettext_lazy('This is the help text'))
170
171 In this example, ``ugettext_lazy()`` stores a lazy reference to the string --
172 not the actual translation. The translation itself will be done when the string
173 is used in a string context, such as template rendering on the Django admin site.
174
175 If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
176 ``_`` (underscore), like so::
177
178     from django.utils.translation import ugettext_lazy as _
179
180     class MyThing(models.Model):
181         name = models.CharField(help_text=_('This is the help text'))
182
183 Always use lazy translations in `Django models`_. It's a good idea to add
184 translations for the field names and table names, too. This means writing
185 explicit ``verbose_name`` and ``verbose_name_plural`` options in the ``Meta``
186 class, though::
187
188     from django.utils.translation import ugettext_lazy as _
189
190     class MyThing(models.Model):
191         name = models.CharField(_('name'), help_text=_('This is the help text'))
192         class Meta:
193             verbose_name = _('my thing')
194             verbose_name_plural = _('mythings')
195
196 .. _Django models: ../model-api/
197
198 Pluralization
199 ~~~~~~~~~~~~~
200
201 Use the function ``django.utils.translation.ungettext()`` to specify pluralized
202 messages. Example::
203
204     from django.utils.translation import ungettext
205     def hello_world(request, count):
206         page = ungettext('there is %(count)d object', 'there are %(count)d objects', count) % {
207             'count': count,
208         }
209         return HttpResponse(page)
210
211 ``ungettext`` takes three arguments: the singular translation string, the plural
212 translation string and the number of objects (which is passed to the
213 translation languages as the ``count`` variable).
214
215 In template code
216 ----------------
217
218 Translations in `Django templates`_ uses two template tags and a slightly
219 different syntax than in Python code. To give your template access to these
220 tags, put ``{% load i18n %}`` toward the top of your template.
221
222 The ``{% trans %}`` template tag translates a constant string or a variable
223 content::
224
225     <title>{% trans "This is the title." %}</title>
226
227 If you only want to mark a value for translation, but translate it later from a
228 variable, use the ``noop`` option::
229
230     <title>{% trans "value" noop %}</title>
231
232 It's not possible to use template variables in ``{% trans %}`` -- only constant
233 strings, in single or double quotes, are allowed. If your translations require
234 variables (placeholders), use ``{% blocktrans %}``. Example::
235
236     {% blocktrans %}This will have {{ value }} inside.{% endblocktrans %}
237
238 To translate a template expression -- say, using template filters -- you need
239 to bind the expression to a local variable for use within the translation
240 block::
241
242     {% blocktrans with value|filter as myvar %}
243     This will have {{ myvar }} inside.
244     {% endblocktrans %}
245
246 If you need to bind more than one expression inside a ``blocktrans`` tag,
247 separate the pieces with ``and``::
248
249     {% blocktrans with book|title as book_t and author|title as author_t %}
250     This is {{ book_t }} by {{ author_t }}
251     {% endblocktrans %}
252
253 To pluralize, specify both the singular and plural forms with the
254 ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
255 ``{% endblocktrans %}``. Example::
256
257     {% blocktrans count list|length as counter %}
258     There is only one {{ name }} object.
259     {% plural %}
260     There are {{ counter }} {{ name }} objects.
261     {% endblocktrans %}
262
263 Internally, all block and inline translations use the appropriate
264 ``ugettext`` / ``ungettext`` call.
265
266 Each ``RequestContext`` has access to three translation-specific variables:
267
268     * ``LANGUAGES`` is a list of tuples in which the first element is the
269       language code and the second is the language name (translated into the
270       currently active locale).
271     * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
272       Example: ``en-us``. (See "How language preference is discovered", below.)
273     * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
274       right-to-left language, e.g: Hebrew, Arabic. If False it's a
275       left-to-right language, e.g: English, French, German etc.
276
277
278 If you don't use the ``RequestContext`` extension, you can get those values with
279 three tags::
280
281     {% get_current_language as LANGUAGE_CODE %}
282     {% get_available_languages as LANGUAGES %}
283     {% get_current_language_bidi as LANGUAGE_BIDI %}
284
285 These tags also require a ``{% load i18n %}``.
286
287 Translation hooks are also available within any template block tag that accepts
288 constant strings. In those cases, just use ``_()`` syntax to specify a
289 translation string. Example::
290
291     {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
292
293 In this case, both the tag and the filter will see the already-translated
294 string, so they don't need to be aware of translations.
295
296 .. note::
297     In this example, the translation infrastructure will be passed the string
298     ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
299     translated string will need to contain the comma so that the filter
300     parsing code knows how to split up the arguments. For example, a German
301     translator might translate the string ``"yes,no"`` as ``"ja,nein"``
302     (keeping the comma intact).
303
304 .. _Django templates: ../templates_python/
305
306 Working with lazy translation objects
307 -------------------------------------
308
309 Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
310 and utility functions is a common operation. When you're working with these
311 objects elsewhere in your code, you should ensure that you don't accidentally
312 convert them to strings, because they should be converted as late as possible
313 (so that the correct locale is in effect). This necessitates the use of a
314 couple of helper functions.
315
316 Joining strings: string_concat()
317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
318
319 Standard Python string joins (``''.join([...])``) will not work on lists
320 containing lazy translation objects. Instead, you can use
321 ``django.utils.translation.string_concat()``, which creates a lazy object that
322 concatenates its contents *and* converts them to strings only when the result
323 is included in a string. For example::
324
325     from django.utils.translation import string_concat
326     ...
327     name = ugettext_lazy(u'John Lennon')
328     instrument = ugettext_lazy(u'guitar')
329     result = string_concat([name, ': ', instrument])
330
331 In this case, the lazy translations in ``result`` will only be converted to
332 strings when ``result`` itself is used in a string (usually at template
333 rendering time).
334
335 The allow_lazy() decorator
336 ~~~~~~~~~~~~~~~~~~~~~~~~~~
337
338 Django offers many utility functions (particularly in ``django.utils``) that
339 take a string as their first argument and do something to that string. These
340 functions are used by template filters as well as directly in other code.
341
342 If you write your own similar functions and deal with translations, you'll
343 face the problem of what to do when the first argument is a lazy translation
344 object. You don't want to convert it to a string immediately, because you might
345 be using this function outside of a view (and hence the current thread's locale
346 setting will not be correct).
347
348 For cases like this, use the  ``django.utils.functional.allow_lazy()``
349 decorator. It modifies the function so that *if* it's called with a lazy
350 translation as the first argument, the function evaluation is delayed until it
351 needs to be converted to a string.
352
353 For example::
354
355     from django.utils.functional import allow_lazy
356
357     def fancy_utility_function(s, ...):
358         # Do some conversion on string 's'
359         ...
360     fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
361
362 The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
363 a number of extra arguments (``*args``) specifying the type(s) that the
364 original function can return. Usually, it's enough to include ``unicode`` here
365 and ensure that your function returns only Unicode strings.
366
367 Using this decorator means you can write your function and assume that the
368 input is a proper string, then add support for lazy translation objects at the
369 end.
370
371 2. How to create language files
372 ===============================
373
374 Once you've tagged your strings for later translation, you need to write (or
375 obtain) the language translations themselves. Here's how that works.
376
377 .. admonition:: Locale restrictions
378
379     Django does not support localizing your application into a locale for
380     which Django itself has not been translated. In this case, it will ignore
381     your translation files. If you were to try this and Django supported it,
382     you would inevitably see a mixture of translated strings (from your
383     application) and English strings (from Django itself). If you want to
384     support a locale for your application that is not already part of
385     Django, you'll need to make at least a minimal translation of the Django
386     core.
387
388 Message files
389 -------------
390
391 The first step is to create a **message file** for a new language. A message
392 file is a plain-text file, representing a single language, that contains all
393 available translation strings and how they should be represented in the given
394 language. Message files have a ``.po`` file extension.
395
396 Django comes with a tool, ``django-admin.py makemessages``, that automates the
397 creation and upkeep of these files.
398
399 .. admonition:: A note to Django veterans
400
401     The old tool ``bin/make-messages.py`` has been moved to the command
402     ``django-admin.py makemessages`` to provide consistency throughout Django.
403
404 To create or update a message file, run this command::
405
406     django-admin.py makemessages -l de
407
408 ...where ``de`` is the language code for the message file you want to create.
409 The language code, in this case, is in locale format. For example, it's
410 ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian German.
411
412 The script should be run from one of three places:
413
414     * The root ``django`` directory (not a Subversion checkout, but the one
415       that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
416       path).
417     * The root directory of your Django project.
418     * The root directory of your Django app.
419
420 The script runs over the entire Django source tree and pulls out all strings
421 marked for translation. It creates (or updates) a message file in the directory
422 ``conf/locale``. In the ``de`` example, the file will be
423 ``conf/locale/de/LC_MESSAGES/django.po``.
424
425 If run over your project source tree or your application source tree, it will
426 do the same, but the location of the locale directory is ``locale/LANG/LC_MESSAGES``
427 (note the missing ``conf`` prefix).
428
429 .. admonition:: No gettext?
430
431     If you don't have the ``gettext`` utilities installed,
432     ``django-admin.py makemessages`` will create empty files. If that's the
433     case, either install the ``gettext`` utilities or just copy the English
434     message file (``conf/locale/en/LC_MESSAGES/django.po``) and use it as a
435     starting point; it's just an empty translation file.
436
437 .. admonition:: Working on Windows?
438
439    If you're using Windows and need to install the GNU gettext utilites so
440    ``django-admin makemessages`` works see `gettext on Windows`_ for more
441    information.
442
443 The format of ``.po`` files is straightforward. Each ``.po`` file contains a
444 small bit of metadata, such as the translation maintainer's contact
445 information, but the bulk of the file is a list of **messages** -- simple
446 mappings between translation strings and the actual translated text for the
447 particular language.
448
449 For example, if your Django app contained a translation string for the text
450 ``"Welcome to my site."``, like so::
451
452     _("Welcome to my site.")
453
454 ...then ``django-admin.py makemessages`` will have created a ``.po`` file
455 containing the following snippet -- a message::
456
457     #: path/to/python/module.py:23
458     msgid "Welcome to my site."
459     msgstr ""
460
461 A quick explanation:
462
463     * ``msgid`` is the translation string, which appears in the source. Don't
464       change it.
465     * ``msgstr`` is where you put the language-specific translation. It starts
466       out empty, so it's your responsibility to change it. Make sure you keep
467       the quotes around your translation.
468     * As a convenience, each message includes the filename and line number
469       from which the translation string was gleaned.
470
471 Long messages are a special case. There, the first string directly after the
472 ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
473 written over the next few lines as one string per line. Those strings are
474 directly concatenated. Don't forget trailing spaces within the strings;
475 otherwise, they'll be tacked together without whitespace!
476
477 .. admonition:: Mind your charset
478
479     When creating a PO file with your favorite text editor, first edit
480     the charset line (search for ``"CHARSET"``) and set it to the charset
481     you'll be using to edit the content. Due to the way the ``gettext`` tools
482     work internally and because we want to allow non-ASCII source strings in
483     Django's core and your applications, you **must** use UTF-8 as the encoding
484     for your PO file. This means that everybody will be using the same
485     encoding, which is important when Django processes the PO files.
486
487 To reexamine all source code and templates for new translation strings and
488 update all message files for **all** languages, run this::
489
490     django-admin.py makemessages -a
491
492 Compiling message files
493 -----------------------
494
495 After you create your message file -- and each time you make changes to it --
496 you'll need to compile it into a more efficient form, for use by ``gettext``.
497 Do this with the ``django-admin.py compilemessages`` utility.
498
499 This tool runs over all available ``.po`` files and creates ``.mo`` files,
500 which are binary files optimized for use by ``gettext``. In the same directory
501 from which you ran ``django-admin.py makemessages``, run
502 ``django-admin.py compilemessages`` like this::
503
504    django-admin.py compilemessages
505
506 That's it. Your translations are ready for use.
507
508 .. admonition:: A note to Django veterans
509
510     The old tool ``bin/compile-messages.py`` has been moved to the command
511     ``django-admin.py compilemessages`` to provide consistency throughout
512     Django.
513
514 .. admonition:: A note to translators
515
516     If you've created a translation in a language Django doesn't yet support,
517     please let us know! See `Submitting and maintaining translations`_ for
518     the steps to take.
519
520     .. _Submitting and maintaining translations: ../contributing/
521
522 .. admonition:: Working on Windows?
523
524    If you're using Windows and need to install the GNU gettext utilites so
525    ``django-admin compilemessages`` works see `gettext on Windows`_ for more
526    information.
527
528 3. How Django discovers language preference
529 ===========================================
530
531 Once you've prepared your translations -- or, if you just want to use the
532 translations that come with Django -- you'll just need to activate translation
533 for your app.
534
535 Behind the scenes, Django has a very flexible model of deciding which language
536 should be used -- installation-wide, for a particular user, or both.
537
538 To set an installation-wide language preference, set ``LANGUAGE_CODE`` in your
539 `settings file`_. Django uses this language as the default translation -- the
540 final attempt if no other translator finds a translation.
541
542 If all you want to do is run Django with your native language, and a language
543 file is available for your language, all you need to do is set
544 ``LANGUAGE_CODE``.
545
546 If you want to let each individual user specify which language he or she
547 prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
548 selection based on data from the request. It customizes content for each user.
549
550 To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
551 to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
552 should follow these guidelines:
553
554     * Make sure it's one of the first middlewares installed.
555     * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
556       makes use of session data.
557     * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
558
559 For example, your ``MIDDLEWARE_CLASSES`` might look like this::
560
561     MIDDLEWARE_CLASSES = (
562        'django.contrib.sessions.middleware.SessionMiddleware',
563        'django.middleware.locale.LocaleMiddleware',
564        'django.middleware.common.CommonMiddleware',
565     )
566
567 (For more on middleware, see the `middleware documentation`_.)
568
569 ``LocaleMiddleware`` tries to determine the user's language preference by
570 following this algorithm:
571
572     * First, it looks for a ``django_language`` key in the the current user's
573       `session`_.
574     * Failing that, it looks for a cookie that is named according to your ``LANGUAGE_COOKIE_NAME`` setting. (The default name is ``django_language``, and this setting is new in the Django development version. In Django version 0.96 and before, the cookie's name is hard-coded to ``django_language``.)
575     * Failing that, it looks at the ``Accept-Language`` HTTP header. This
576       header is sent by your browser and tells the server which language(s) you
577       prefer, in order by priority. Django tries each language in the header
578       until it finds one with available translations.
579     * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
580
581 Notes:
582
583     * In each of these places, the language preference is expected to be in the
584       standard language format, as a string. For example, Brazilian Portuguese
585       is ``pt-br``.
586     * If a base language is available but the sublanguage specified is not,
587       Django uses the base language. For example, if a user specifies ``de-at``
588       (Austrian German) but Django only has ``de`` available, Django uses
589       ``de``.
590     * Only languages listed in the `LANGUAGES setting`_ can be selected. If
591       you want to restrict the language selection to a subset of provided
592       languages (because your application doesn't provide all those languages),
593       set ``LANGUAGES`` to a list of languages. For example::
594
595           LANGUAGES = (
596             ('de', _('German')),
597             ('en', _('English')),
598           )
599
600       This example restricts languages that are available for automatic
601       selection to German and English (and any sublanguage, like de-ch or
602       en-us).
603
604       .. _LANGUAGES setting: ../settings/#languages
605
606     * If you define a custom ``LANGUAGES`` setting, as explained in the
607       previous bullet, it's OK to mark the languages as translation strings
608       -- but use a "dummy" ``ugettext()`` function, not the one in
609       ``django.utils.translation``. You should *never* import
610       ``django.utils.translation`` from within your settings file, because that
611       module in itself depends on the settings, and that would cause a circular
612       import.
613
614       The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
615       settings file::
616
617           ugettext = lambda s: s
618
619           LANGUAGES = (
620               ('de', ugettext('German')),
621               ('en', ugettext('English')),
622           )
623
624       With this arrangement, ``django-admin.py makemessages`` will still find
625       and mark these strings for translation, but the translation won't happen
626       at runtime -- so you'll have to remember to wrap the languages in the *real*
627       ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
628
629     * The ``LocaleMiddleware`` can only select languages for which there is a
630       Django-provided base translation. If you want to provide translations
631       for your application that aren't already in the set of translations
632       in Django's source tree, you'll want to provide at least basic
633       translations for that language. For example, Django uses technical
634       message IDs to translate date formats and time formats -- so you will
635       need at least those translations for the system to work correctly.
636
637       A good starting point is to copy the English ``.po`` file and to
638       translate at least the technical messages -- maybe the validator
639       messages, too.
640
641       Technical message IDs are easily recognized; they're all upper case. You
642       don't translate the message ID as with other messages, you provide the
643       correct local variant on the provided English value. For example, with
644       ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
645       be the format string that you want to use in your language. The format
646       is identical to the format strings used by the ``now`` template tag.
647
648 Once ``LocaleMiddleware`` determines the user's preference, it makes this
649 preference available as ``request.LANGUAGE_CODE`` for each `request object`_.
650 Feel free to read this value in your view code. Here's a simple example::
651
652     def hello_world(request, count):
653         if request.LANGUAGE_CODE == 'de-at':
654             return HttpResponse("You prefer to read Austrian German.")
655         else:
656             return HttpResponse("You prefer to read another language.")
657
658 Note that, with static (middleware-less) translation, the language is in
659 ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
660 in ``request.LANGUAGE_CODE``.
661
662 .. _settings file: ../settings/
663 .. _middleware documentation: ../middleware/
664 .. _session: ../sessions/
665 .. _request object: ../request_response/#httprequest-objects
666
667 Using translations in your own projects
668 =======================================
669
670 Django looks for translations by following this algorithm:
671
672     * First, it looks for a ``locale`` directory in the application directory
673       of the view that's being called. If it finds a translation for the
674       selected language, the translation will be installed.
675     * Next, it looks for a ``locale`` directory in the project directory. If it
676       finds a translation, the translation will be installed.
677     * Finally, it checks the base translation in ``django/conf/locale``.
678
679 This way, you can write applications that include their own translations, and
680 you can override base translations in your project path. Or, you can just build
681 a big project out of several apps and put all translations into one big project
682 message file. The choice is yours.
683
684 .. note::
685
686     If you're using manually configured settings, as described in the
687     `settings documentation`_, the ``locale`` directory in the project
688     directory will not be examined, since Django loses the ability to work out
689     the location of the project directory. (Django normally uses the location
690     of the settings file to determine this, and a settings file doesn't exist
691     if you're manually configuring your settings.)
692
693 .. _settings documentation: ../settings/#using-settings-without-setting-django-settings-module
694
695 All message file repositories are structured the same way. They are:
696
697     * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
698     * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
699     * All paths listed in ``LOCALE_PATHS`` in your settings file are
700       searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
701     * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
702
703 To create message files, you use the same ``django-admin.py makemessages``
704 tool as with the Django message files. You only need to be in the right place
705 -- in the directory where either the ``conf/locale`` (in case of the source
706 tree) or the ``locale/`` (in case of app messages or project messages)
707 directory are located. And you use the same ``django-admin.py compilemessages``
708 to produce the binary ``django.mo`` files that are used by ``gettext``.
709
710 You can also run ``django-admin.py compilemessages --settings=path.to.settings``
711 to make the compiler process all the directories in your ``LOCALE_PATHS``
712 setting.
713
714 Application message files are a bit complicated to discover -- they need the
715 ``LocaleMiddleware``. If you don't use the middleware, only the Django message
716 files and project message files will be processed.
717
718 Finally, you should give some thought to the structure of your translation
719 files. If your applications need to be delivered to other users and will
720 be used in other projects, you might want to use app-specific translations.
721 But using app-specific translations and project translations could produce
722 weird problems with ``makemessages``: ``makemessages`` will traverse all
723 directories below the current path and so might put message IDs into the
724 project message file that are already in application message files.
725
726 The easiest way out is to store applications that are not part of the project
727 (and so carry their own translations) outside the project tree. That way,
728 ``django-admin.py makemessages`` on the project level will only translate
729 strings that are connected to your explicit project and not strings that are
730 distributed independently.
731
732 The ``set_language`` redirect view
733 ==================================
734
735 As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
736 that sets a user's language preference and redirects back to the previous page.
737
738 Activate this view by adding the following line to your URLconf::
739
740     (r'^i18n/', include('django.conf.urls.i18n')),
741
742 (Note that this example makes the view available at ``/i18n/setlang/``.)
743
744 The view expects to be called via the ``POST`` method, with a ``language``
745 parameter set in request. If session support is enabled, the view
746 saves the language choice in the user's session. Otherwise, it saves the
747 language choice in a cookie that is by default named ``django_language``.
748 (The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting if you're
749 using the Django development version.)
750
751 After setting the language choice, Django redirects the user, following this
752 algorithm:
753
754     * Django looks for a ``next`` parameter in the ``POST`` data.
755     * If that doesn't exist, or is empty, Django tries the URL in the
756       ``Referrer`` header.
757     * If that's empty -- say, if a user's browser suppresses that header --
758       then the user will be redirected to ``/`` (the site root) as a fallback.
759
760 Here's example HTML template code::
761
762     <form action="/i18n/setlang/" method="post">
763     <input name="next" type="hidden" value="/next/page/" />
764     <select name="language">
765     {% for lang in LANGUAGES %}
766     <option value="{{ lang.0 }}">{{ lang.1 }}</option>
767     {% endfor %}
768     </select>
769     <input type="submit" value="Go" />
770     </form>
771
772 Translations and JavaScript
773 ===========================
774
775 Adding translations to JavaScript poses some problems:
776
777     * JavaScript code doesn't have access to a ``gettext`` implementation.
778
779     * JavaScript code doesn't have access to .po or .mo files; they need to be
780       delivered by the server.
781
782     * The translation catalogs for JavaScript should be kept as small as
783       possible.
784
785 Django provides an integrated solution for these problems: It passes the
786 translations into JavaScript, so you can call ``gettext``, etc., from within
787 JavaScript.
788
789 The ``javascript_catalog`` view
790 -------------------------------
791
792 The main solution to these problems is the ``javascript_catalog`` view, which
793 sends out a JavaScript code library with functions that mimic the ``gettext``
794 interface, plus an array of translation strings. Those translation strings are
795 taken from the application, project or Django core, according to what you
796 specify in either the info_dict or the URL.
797
798 You hook it up like this::
799
800     js_info_dict = {
801         'packages': ('your.app.package',),
802     }
803
804     urlpatterns = patterns('',
805         (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
806     )
807
808 Each string in ``packages`` should be in Python dotted-package syntax (the
809 same format as the strings in ``INSTALLED_APPS``) and should refer to a package
810 that contains a ``locale`` directory. If you specify multiple packages, all
811 those catalogs are merged into one catalog. This is useful if you have
812 JavaScript that uses strings from different applications.
813
814 You can make the view dynamic by putting the packages into the URL pattern::
815
816     urlpatterns = patterns('',
817         (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
818     )
819
820 With this, you specify the packages as a list of package names delimited by '+'
821 signs in the URL. This is especially useful if your pages use code from
822 different apps and this changes often and you don't want to pull in one big
823 catalog file. As a security measure, these values can only be either
824 ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
825
826 Using the JavaScript translation catalog
827 ----------------------------------------
828
829 To use the catalog, just pull in the dynamically generated script like this::
830
831     <script type="text/javascript" src="/path/to/jsi18n/"></script>
832
833 This is how the admin fetches the translation catalog from the server. When the
834 catalog is loaded, your JavaScript code can use the standard ``gettext``
835 interface to access it::
836
837     document.write(gettext('this is to be translated'));
838
839 There is also an ``ngettext`` interface::
840
841     var object_cnt = 1 // or 0, or 2, or 3, ...
842     s = ngettext('literal for the singular case',
843             'literal for the plural case', object_cnt);
844
845 and even a string interpolation function::
846
847     function interpolate(fmt, obj, named);
848
849 The interpolation syntax is borrowed from Python, so the ``interpolate``
850 function supports both positional and named interpolation:
851
852     * Positional interpolation: ``obj`` contains a JavaScript Array object
853       whose elements values are then sequentially interpolated in their
854       corresponding ``fmt`` placeholders in the same order they appear.
855       For example::
856
857         fmts = ngettext('There is %s object. Remaining: %s',
858                 'There are %s objects. Remaining: %s', 11);
859         s = interpolate(fmts, [11, 20]);
860         // s is 'There are 11 objects. Remaining: 20'
861
862     * Named interpolation: This mode is selected by passing the optional
863       boolean ``named`` parameter as true. ``obj`` contains a JavaScript
864       object or associative array. For example::
865
866         d = {
867             count: 10
868             total: 50
869         };
870
871         fmts = ngettext('Total: %(total)s, there is %(count)s object',
872         'there are %(count)s of a total of %(total)s objects', d.count);
873         s = interpolate(fmts, d, true);
874
875 You shouldn't go over the top with string interpolation, though: this is still
876 JavaScript, so the code has to make repeated regular-expression substitutions.
877 This isn't as fast as string interpolation in Python, so keep it to those
878 cases where you really need it (for example, in conjunction with ``ngettext``
879 to produce proper pluralizations).
880
881 Creating JavaScript translation catalogs
882 ----------------------------------------
883
884 You create and update the translation catalogs the same way as the other
885 Django translation catalogs -- with the django-admin.py makemessages tool. The
886 only difference is you need to provide a ``-d djangojs`` parameter, like this::
887
888     django-admin.py makemessages -d djangojs -l de
889
890 This would create or update the translation catalog for JavaScript for German.
891 After updating translation catalogs, just run ``django-admin.py compilemessages``
892 the same way as you do with normal Django translation catalogs.
893
894 Specialties of Django translation
895 ==================================
896
897 If you know ``gettext``, you might note these specialties in the way Django
898 does translation:
899
900     * The string domain is ``django`` or ``djangojs``. This string domain is
901       used to differentiate between different programs that store their data
902       in a common message-file library (usually ``/usr/share/locale/``). The
903       ``django`` domain is used for Python and template translation strings
904       and is loaded into the global translation catalogs. The ``djangojs``
905       domain is only used for JavaScript translation catalogs to make sure
906       that those are as small as possible.
907     * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
908       ``xgettext`` and ``msgfmt``. This is mostly for convenience.
909
910 ``gettext`` on Windows
911 ======================
912
913 This is only needed for people who either want to extract message IDs or
914 compile ``.po`` files. Translation work itself just involves editing existing
915 ``.po`` files, but if you want to create your own .po files, or want to test
916 or compile a changed ``.po`` file, you will need the ``gettext`` utilities:
917
918     * Download the following zip files from http://sourceforge.net/projects/gettext
919
920       * ``gettext-runtime-X.bin.woe32.zip``
921       * ``gettext-tools-X.bin.woe32.zip``
922       * ``libiconv-X.bin.woe32.zip``
923
924     * Extract the 3 files in the same folder (i.e. ``C:\Program Files\gettext-utils``)
925
926     * Update the system PATH:
927
928       * ``Control Panel > System > Advanced > Environment Variables``
929       * In the ``System variables`` list, click ``Path``, click ``Edit``
930       * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the ``Variable value``
Note: See TracBrowser for help on using the browser.