Fixed #5550: Documented the context used by the default view for 404 and 500 errors.
[django.git] / docs / i18n.txt
blob1ae302415715ed17e8f9a04b88e0db44ee063d17
1 ====================
2 Internationalization
3 ====================
5 Django has full support for internationalization of text in code and templates.
6 Here's how it works.
8 Overview
9 ========
11 The goal of internationalization is to allow a single Web application to offer
12 its content and functionality in multiple languages.
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."
20 Django takes care of using these hooks to translate Web apps, on the fly,
21 according to users' language preferences.
23 Essentially, Django does two things:
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.
30 If you don't need internationalization in your app
31 ==================================================
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`_.
40 You'll probably also want to remove ``'django.core.context_processors.i18n'``
41 from your ``TEMPLATE_CONTEXT_PROCESSORS`` setting.
43 .. _documentation for USE_I18N: ../settings/#use-i18n
45 If you do need internationalization: three steps
46 ================================================
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.
53 .. admonition:: Behind the scenes
55     Django's translation machinery uses the standard ``gettext`` module that
56     comes with Python.
58 1. How to specify translation strings
59 =====================================
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.
65 In Python code
66 --------------
68 Standard translation
69 ~~~~~~~~~~~~~~~~~~~~
71 Specify a translation string by using the function ``ugettext()``. It's
72 convention to import this as a shorter alias, ``_``, to save typing.
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:
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.
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.
90 In this example, the text ``"Welcome to my site."`` is marked as a translation
91 string::
93     from django.utils.translation import ugettext as _
95     def my_view(request):
96         output = _("Welcome to my site.")
97         return HttpResponse(output)
99 Obviously, you could code this without using the alias. This example is
100 identical to the previous one::
102     from django.utils.translation import ugettext
104     def my_view(request):
105         output = ugettext("Welcome to my site.")
106         return HttpResponse(output)
108 Translation works on computed values. This example is identical to the previous
109 two::
111     def my_view(request):
112         words = ['Welcome', 'to', 'my', 'site.']
113         output = _(' '.join(words))
114         return HttpResponse(output)
116 Translation works on variables. Again, here's an identical example::
118     def my_view(request):
119         sentence = 'Welcome to my site.'
120         output = _(sentence)
121         return HttpResponse(output)
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 ``make-messages.py``, won't be able to find these strings. More on
126 ``make-messages`` later.)
128 The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
129 specified with Python's standard named-string interpolation syntax. Example::
131     def my_view(request, n):
132         output = _('%(name)s is my name.') % {'name': n}
133         return HttpResponse(output)
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.
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.
145 Marking strings as no-op
146 ~~~~~~~~~~~~~~~~~~~~~~~~
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.
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.
157 Lazy translation
158 ~~~~~~~~~~~~~~~~
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.
164 For example, to translate a model's ``help_text``, do the following::
166     from django.utils.translation import ugettext_lazy
168     class MyThing(models.Model):
169         name = models.CharField(help_text=ugettext_lazy('This is the help text'))
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.
175 If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
176 ``_`` (underscore), like so::
178     from django.utils.translation import ugettext_lazy as _
180     class MyThing(models.Model):
181         name = models.CharField(help_text=_('This is the help text'))
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::
188     from django.utils.translation import ugettext_lazy as _
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')
196 .. _Django models: ../model-api/
198 Pluralization
199 ~~~~~~~~~~~~~
201 Use the function ``django.utils.translation.ungettext()`` to specify pluralized
202 messages. Example::
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)
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).
215 In template code
216 ----------------
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.
222 The ``{% trans %}`` template tag translates a constant string or a variable
223 content::
225     <title>{% trans "This is the title." %}</title>
227 If you only want to mark a value for translation, but translate it later from a
228 variable, use the ``noop`` option::
230     <title>{% trans "value" noop %}</title>
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::
236     {% blocktrans %}This will have {{ value }} inside.{% endblocktrans %}
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::
242     {% blocktrans with value|filter as myvar %}
243     This will have {{ myvar }} inside.
244     {% endblocktrans %}
246 If you need to bind more than one expression inside a ``blocktrans`` tag,
247 separate the pieces with ``and``::
249     {% blocktrans with book|title as book_t and author|title as author_t %}
250     This is {{ book_t }} by {{ author_t }}
251     {% endblocktrans %}
253 To pluralize, specify both the singular and plural forms with the
254 ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
255 ``{% endblocktrans %}``. Example::
257     {% blocktrans count list|length as counter %}
258     There is only one {{ name }} object.
259     {% plural %}
260     There are {{ counter }} {{ name }} objects.
261     {% endblocktrans %}
263 Internally, all block and inline translations use the appropriate
264 ``ugettext`` / ``ungettext`` call.
266 Each ``RequestContext`` has access to three translation-specific variables:
268     * ``LANGUAGES`` is a list of tuples in which the first element is the
269       language code and the second is the language name (in that language).
270     * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
271       Example: ``en-us``. (See "How language preference is discovered", below.)
272     * ``LANGUAGE_BIDI`` is the current language's direction. If True, it's a
273       right-to-left language, e.g: Hebrew, Arabic. If False it's a
274       left-to-right language, e.g: English, French, German etc.
277 If you don't use the ``RequestContext`` extension, you can get those values with
278 three tags::
280     {% get_current_language as LANGUAGE_CODE %}
281     {% get_available_languages as LANGUAGES %}
282     {% get_current_language_bidi as LANGUAGE_BIDI %}
284 These tags also require a ``{% load i18n %}``.
286 Translation hooks are also available within any template block tag that accepts
287 constant strings. In those cases, just use ``_()`` syntax to specify a
288 translation string. Example::
290     {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
292 In this case, both the tag and the filter will see the already-translated
293 string, so they don't need to be aware of translations.
295 .. _Django templates: ../templates_python/
297 Working with lazy translation objects
298 -------------------------------------
300 Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
301 and utility functions is a common operation. When you're working with these
302 objects elsewhere in your code, you should ensure that you don't accidentally
303 convert them to strings, because they should be converted as late as possible
304 (so that the correct locale is in effect). This necessitates the use of a
305 couple of helper functions.
307 Joining strings: string_concat()
308 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310 Standard Python string joins (``''.join([...])``) will not work on lists
311 containing lazy translation objects. Instead, you can use
312 ``django.utils.translation.string_concat()``, which creates a lazy object that
313 concatenates its contents *and* converts them to strings only when the result
314 is included in a string. For example::
316     from django.utils.translation import string_concat
317     ...
318     name = ugettext_lazy(u'John Lennon')
319     instrument = ugettext_lazy(u'guitar')
320     result = string_concat([name, ': ', instrument])
322 In this case, the lazy translations in ``result`` will only be converted to
323 strings when ``result`` itself is used in a string (usually at template
324 rendering time).
326 The allow_lazy() decorator
327 ~~~~~~~~~~~~~~~~~~~~~~~~~~
329 Django offers many utility functions (particularly in ``django.utils``) that
330 take a string as their first argument and do something to that string. These
331 functions are used by template filters as well as directly in other code.
333 If you write your own similar functions and deal with translations, you'll 
334 face the problem of what to do when the first argument is a lazy translation
335 object. You don't want to convert it to a string immediately, because you might
336 be using this function outside of a view (and hence the current thread's locale
337 setting will not be correct).
339 For cases like this, use the  ``django.utils.functional.allow_lazy()``
340 decorator. It modifies the function so that *if* it's called with a lazy
341 translation as the first argument, the function evaluation is delayed until it
342 needs to be converted to a string.
344 For example::
346     from django.utils.functional import allow_lazy
348     def fancy_utility_function(s, ...):
349         # Do some conversion on string 's'
350         ...
351     fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
353 The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
354 a number of extra arguments (``*args``) specifying the type(s) that the
355 original function can return. Usually, it's enough to include ``unicode`` here
356 and ensure that your function returns only Unicode strings.
358 Using this decorator means you can write your function and assume that the
359 input is a proper string, then add support for lazy translation objects at the
360 end.
362 2. How to create language files
363 ===============================
365 Once you've tagged your strings for later translation, you need to write (or
366 obtain) the language translations themselves. Here's how that works.
368 .. admonition:: Locale restrictions
370     Django does not support localizing your application into a locale for
371     which Django itself has not been translated. In this case, it will ignore
372     your translation files. If you were to try this and Django supported it,
373     you would inevitably see a mixture of translated strings (from your
374     application) and English strings (from Django itself). If you want to
375     support a locale for your application that is not already part of
376     Django, you'll need to make at least a minimal translation of the Django
377     core.
379 Message files
380 -------------
382 The first step is to create a **message file** for a new language. A message
383 file is a plain-text file, representing a single language, that contains all
384 available translation strings and how they should be represented in the given
385 language. Message files have a ``.po`` file extension.
387 Django comes with a tool, ``bin/make-messages.py``, that automates the creation
388 and upkeep of these files.
390 To create or update a message file, run this command::
392     bin/make-messages.py -l de
394 ...where ``de`` is the language code for the message file you want to create.
395 The language code, in this case, is in locale format. For example, it's
396 ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian German.
398 The script should be run from one of three places:
400     * The root ``django`` directory (not a Subversion checkout, but the one
401       that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
402       path).
403     * The root directory of your Django project.
404     * The root directory of your Django app.
406 The script runs over the entire Django source tree and pulls out all strings
407 marked for translation. It creates (or updates) a message file in the directory
408 ``conf/locale``. In the ``de`` example, the file will be
409 ``conf/locale/de/LC_MESSAGES/django.po``.
411 If run over your project source tree or your application source tree, it will
412 do the same, but the location of the locale directory is ``locale/LANG/LC_MESSAGES``
413 (note the missing ``conf`` prefix).
415 .. admonition:: No gettext?
417     If you don't have the ``gettext`` utilities installed, ``make-messages.py``
418     will create empty files. If that's the case, either install the ``gettext``
419     utilities or just copy the English message file
420     (``conf/locale/en/LC_MESSAGES/django.po``) and use it as a starting point;
421     it's just an empty translation file.
423 The format of ``.po`` files is straightforward. Each ``.po`` file contains a
424 small bit of metadata, such as the translation maintainer's contact
425 information, but the bulk of the file is a list of **messages** -- simple
426 mappings between translation strings and the actual translated text for the
427 particular language.
429 For example, if your Django app contained a translation string for the text
430 ``"Welcome to my site."``, like so::
432     _("Welcome to my site.")
434 ...then ``make-messages.py`` will have created a ``.po`` file containing the
435 following snippet -- a message::
437     #: path/to/python/module.py:23
438     msgid "Welcome to my site."
439     msgstr ""
441 A quick explanation:
443     * ``msgid`` is the translation string, which appears in the source. Don't
444       change it.
445     * ``msgstr`` is where you put the language-specific translation. It starts
446       out empty, so it's your responsibility to change it. Make sure you keep
447       the quotes around your translation.
448     * As a convenience, each message includes the filename and line number
449       from which the translation string was gleaned.
451 Long messages are a special case. There, the first string directly after the
452 ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
453 written over the next few lines as one string per line. Those strings are
454 directly concatenated. Don't forget trailing spaces within the strings;
455 otherwise, they'll be tacked together without whitespace!
457 .. admonition:: Mind your charset
459     When creating a PO file with your favorite text editor, first edit
460     the charset line (search for ``"CHARSET"``) and set it to the charset
461     you'll be using to edit the content. Due to the way the ``gettext`` tools
462     work internally and because we want to allow non-ASCII source strings in
463     Django's core and your applications, you **must** use UTF-8 as the encoding
464     for your PO file. This means that everybody will be using the same
465     encoding, which is important when Django processes the PO files.
467 To reexamine all source code and templates for new translation strings and
468 update all message files for **all** languages, run this::
470     make-messages.py -a
472 Compiling message files
473 -----------------------
475 After you create your message file -- and each time you make changes to it --
476 you'll need to compile it into a more efficient form, for use by ``gettext``.
477 Do this with the ``bin/compile-messages.py`` utility.
479 This tool runs over all available ``.po`` files and creates ``.mo`` files,
480 which are binary files optimized for use by ``gettext``. In the same directory
481 from which you ran ``make-messages.py``, run ``compile-messages.py`` like
482 this::
484    bin/compile-messages.py
486 That's it. Your translations are ready for use.
488 .. admonition:: A note to translators
490     If you've created a translation in a language Django doesn't yet support,
491     please let us know! See `Submitting and maintaining translations`_ for
492     the steps to take.
494     .. _Submitting and maintaining translations: ../contributing/
496 3. How Django discovers language preference
497 ===========================================
499 Once you've prepared your translations -- or, if you just want to use the
500 translations that come with Django -- you'll just need to activate translation
501 for your app.
503 Behind the scenes, Django has a very flexible model of deciding which language
504 should be used -- installation-wide, for a particular user, or both.
506 To set an installation-wide language preference, set ``LANGUAGE_CODE`` in your
507 `settings file`_. Django uses this language as the default translation -- the
508 final attempt if no other translator finds a translation.
510 If all you want to do is run Django with your native language, and a language
511 file is available for your language, all you need to do is set
512 ``LANGUAGE_CODE``.
514 If you want to let each individual user specify which language he or she
515 prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
516 selection based on data from the request. It customizes content for each user.
518 To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
519 to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
520 should follow these guidelines:
522     * Make sure it's one of the first middlewares installed.
523     * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
524       makes use of session data.
525     * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
527 For example, your ``MIDDLEWARE_CLASSES`` might look like this::
529     MIDDLEWARE_CLASSES = (
530        'django.contrib.sessions.middleware.SessionMiddleware',
531        'django.middleware.locale.LocaleMiddleware',
532        'django.middleware.common.CommonMiddleware',
533     )
535 (For more on middleware, see the `middleware documentation`_.)
537 ``LocaleMiddleware`` tries to determine the user's language preference by
538 following this algorithm:
540     * First, it looks for a ``django_language`` key in the the current user's
541       `session`_.
542     * Failing that, it looks for a cookie called ``django_language``.
543     * Failing that, it looks at the ``Accept-Language`` HTTP header. This
544       header is sent by your browser and tells the server which language(s) you
545       prefer, in order by priority. Django tries each language in the header
546       until it finds one with available translations.
547     * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
549 Notes:
551     * In each of these places, the language preference is expected to be in the
552       standard language format, as a string. For example, Brazilian Portuguese
553       is ``pt-br``.
554     * If a base language is available but the sublanguage specified is not,
555       Django uses the base language. For example, if a user specifies ``de-at``
556       (Austrian German) but Django only has ``de`` available, Django uses
557       ``de``.
558     * Only languages listed in the `LANGUAGES setting`_ can be selected. If
559       you want to restrict the language selection to a subset of provided
560       languages (because your application doesn't provide all those languages),
561       set ``LANGUAGES`` to a list of languages. For example::
563           LANGUAGES = (
564             ('de', _('German')),
565             ('en', _('English')),
566           )
568       This example restricts languages that are available for automatic
569       selection to German and English (and any sublanguage, like de-ch or
570       en-us).
572       .. _LANGUAGES setting: ../settings/#languages
574     * If you define a custom ``LANGUAGES`` setting, as explained in the
575       previous bullet, it's OK to mark the languages as translation strings
576       -- but use a "dummy" ``ugettext()`` function, not the one in
577       ``django.utils.translation``. You should *never* import
578       ``django.utils.translation`` from within your settings file, because that
579       module in itself depends on the settings, and that would cause a circular
580       import.
582       The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
583       settings file::
585           ugettext = lambda s: s
587           LANGUAGES = (
588               ('de', ugettext('German')),
589               ('en', ugettext('English')),
590           )
592       With this arrangement, ``make-messages.py`` will still find and mark
593       these strings for translation, but the translation won't happen at
594       runtime -- so you'll have to remember to wrap the languages in the *real*
595       ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
597     * The ``LocaleMiddleware`` can only select languages for which there is a
598       Django-provided base translation. If you want to provide translations
599       for your application that aren't already in the set of translations
600       in Django's source tree, you'll want to provide at least basic
601       translations for that language. For example, Django uses technical
602       message IDs to translate date formats and time formats -- so you will
603       need at least those translations for the system to work correctly.
605       A good starting point is to copy the English ``.po`` file and to
606       translate at least the technical messages -- maybe the validator
607       messages, too.
609       Technical message IDs are easily recognized; they're all upper case. You
610       don't translate the message ID as with other messages, you provide the
611       correct local variant on the provided English value. For example, with
612       ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
613       be the format string that you want to use in your language. The format
614       is identical to the format strings used by the ``now`` template tag.
616 Once ``LocaleMiddleware`` determines the user's preference, it makes this
617 preference available as ``request.LANGUAGE_CODE`` for each `request object`_.
618 Feel free to read this value in your view code. Here's a simple example::
620     def hello_world(request, count):
621         if request.LANGUAGE_CODE == 'de-at':
622             return HttpResponse("You prefer to read Austrian German.")
623         else:
624             return HttpResponse("You prefer to read another language.")
626 Note that, with static (middleware-less) translation, the language is in
627 ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
628 in ``request.LANGUAGE_CODE``.
630 .. _settings file: ../settings/
631 .. _middleware documentation: ../middleware/
632 .. _session: ../sessions/
633 .. _request object: ../request_response/#httprequest-objects
635 Using translations in your own projects
636 =======================================
638 Django looks for translations by following this algorithm:
640     * First, it looks for a ``locale`` directory in the application directory
641       of the view that's being called. If it finds a translation for the
642       selected language, the translation will be installed.
643     * Next, it looks for a ``locale`` directory in the project directory. If it
644       finds a translation, the translation will be installed.
645     * Finally, it checks the base translation in ``django/conf/locale``.
647 This way, you can write applications that include their own translations, and
648 you can override base translations in your project path. Or, you can just build
649 a big project out of several apps and put all translations into one big project
650 message file. The choice is yours.
652 .. note::
654     If you're using manually configured settings, as described in the
655     `settings documentation`_, the ``locale`` directory in the project
656     directory will not be examined, since Django loses the ability to work out
657     the location of the project directory. (Django normally uses the location
658     of the settings file to determine this, and a settings file doesn't exist
659     if you're manually configuring your settings.)
661 .. _settings documentation: ../settings/#using-settings-without-setting-django-settings-module
663 All message file repositories are structured the same way. They are:
665     * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
666     * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
667     * All paths listed in ``LOCALE_PATHS`` in your settings file are
668       searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
669     * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
671 To create message files, you use the same ``make-messages.py`` tool as with the
672 Django message files. You only need to be in the right place -- in the directory
673 where either the ``conf/locale`` (in case of the source tree) or the ``locale/``
674 (in case of app messages or project messages) directory are located. And you
675 use the same ``compile-messages.py`` to produce the binary ``django.mo`` files
676 that are used by ``gettext``.
678 You can also run ``compile-message.py --settings=path.to.settings`` to make
679 the compiler process all the directories in your ``LOCALE_PATHS`` setting.
681 Application message files are a bit complicated to discover -- they need the
682 ``LocaleMiddleware``. If you don't use the middleware, only the Django message
683 files and project message files will be processed.
685 Finally, you should give some thought to the structure of your translation
686 files. If your applications need to be delivered to other users and will
687 be used in other projects, you might want to use app-specific translations.
688 But using app-specific translations and project translations could produce
689 weird problems with ``make-messages``: ``make-messages`` will traverse all
690 directories below the current path and so might put message IDs into the
691 project message file that are already in application message files.
693 The easiest way out is to store applications that are not part of the project
694 (and so carry their own translations) outside the project tree. That way,
695 ``make-messages`` on the project level will only translate strings that are
696 connected to your explicit project and not strings that are distributed
697 independently.
699 The ``set_language`` redirect view
700 ==================================
702 As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
703 that sets a user's language preference and redirects back to the previous page.
705 Activate this view by adding the following line to your URLconf::
707     (r'^i18n/', include('django.conf.urls.i18n')),
709 (Note that this example makes the view available at ``/i18n/setlang/``.)
711 The view expects to be called via the ``POST`` method, with a ``language``
712 parameter set in request. If session support is enabled, the view
713 saves the language choice in the user's session. Otherwise, it saves the
714 language choice in a ``django_language`` cookie.
716 After setting the language choice, Django redirects the user, following this
717 algorithm:
719     * Django looks for a ``next`` parameter in the ``POST`` data.
720     * If that doesn't exist, or is empty, Django tries the URL in the
721       ``Referrer`` header.
722     * If that's empty -- say, if a user's browser suppresses that header --
723       then the user will be redirected to ``/`` (the site root) as a fallback.
725 Here's example HTML template code::
727     <form action="/i18n/setlang/" method="post">
728     <input name="next" type="hidden" value="/next/page/" />
729     <select name="language">
730     {% for lang in LANGUAGES %}
731     <option value="{{ lang.0 }}">{{ lang.1 }}</option>
732     {% endfor %}
733     </select>
734     <input type="submit" value="Go" />
735     </form>
737 Translations and JavaScript
738 ===========================
740 Adding translations to JavaScript poses some problems:
742     * JavaScript code doesn't have access to a ``gettext`` implementation.
744     * JavaScript code doesn't have access to .po or .mo files; they need to be
745       delivered by the server.
747     * The translation catalogs for JavaScript should be kept as small as
748       possible.
750 Django provides an integrated solution for these problems: It passes the
751 translations into JavaScript, so you can call ``gettext``, etc., from within
752 JavaScript.
754 The ``javascript_catalog`` view
755 -------------------------------
757 The main solution to these problems is the ``javascript_catalog`` view, which
758 sends out a JavaScript code library with functions that mimic the ``gettext``
759 interface, plus an array of translation strings. Those translation strings are
760 taken from the application, project or Django core, according to what you
761 specify in either the info_dict or the URL.
763 You hook it up like this::
765     js_info_dict = {
766         'packages': ('your.app.package',),
767     }
769     urlpatterns = patterns('',
770         (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
771     )
773 Each string in ``packages`` should be in Python dotted-package syntax (the
774 same format as the strings in ``INSTALLED_APPS``) and should refer to a package
775 that contains a ``locale`` directory. If you specify multiple packages, all
776 those catalogs are merged into one catalog. This is useful if you have
777 JavaScript that uses strings from different applications.
779 You can make the view dynamic by putting the packages into the URL pattern::
781     urlpatterns = patterns('',
782         (r'^jsi18n/(?P<packages>\S+?)/$, 'django.views.i18n.javascript_catalog'),
783     )
785 With this, you specify the packages as a list of package names delimited by '+'
786 signs in the URL. This is especially useful if your pages use code from
787 different apps and this changes often and you don't want to pull in one big
788 catalog file. As a security measure, these values can only be either
789 ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
791 Using the JavaScript translation catalog
792 ----------------------------------------
794 To use the catalog, just pull in the dynamically generated script like this::
796     <script type="text/javascript" src="/path/to/jsi18n/"></script>
798 This is how the admin fetches the translation catalog from the server. When the
799 catalog is loaded, your JavaScript code can use the standard ``gettext``
800 interface to access it::
802     document.write(gettext('this is to be translated'));
804 There even is a ``ungettext`` interface and a string interpolation function::
806     d = {
807         count: 10
808     };
809     s = interpolate(ungettext('this is %(count)s object', 'this are %(count)s objects', d.count), d);
811 The ``interpolate`` function supports both positional interpolation and named
812 interpolation. So the above could have been written as::
814     s = interpolate(ungettext('this is %s object', 'this are %s objects', 11), [11]);
816 The interpolation syntax is borrowed from Python. You shouldn't go over the top
817 with string interpolation, though: this is still JavaScript, so the code will
818 have to do repeated regular-expression substitutions. This isn't as fast as
819 string interpolation  in Python, so keep it to those cases where you really
820 need it (for example, in conjunction with ``ungettext`` to produce proper
821 pluralizations).
823 Creating JavaScript translation catalogs
824 ----------------------------------------
826 You create and update the translation catalogs the same way as the other
827 Django translation catalogs -- with the make-messages.py tool. The only
828 difference is you need to provide a ``-d djangojs`` parameter, like this::
830     make-messages.py -d djangojs -l de
832 This would create or update the translation catalog for JavaScript for German.
833 After updating translation catalogs, just run ``compile-messages.py`` the same
834 way as you do with normal Django translation catalogs.
836 Specialties of Django translation
837 ==================================
839 If you know ``gettext``, you might note these specialties in the way Django
840 does translation:
842     * The string domain is ``django`` or ``djangojs``. This string domain is
843       used to differentiate between different programs that store their data
844       in a common message-file library (usually ``/usr/share/locale/``). The
845       ``django`` domain is used for python and template translation strings
846       and is loaded into the global translation catalogs. The ``djangojs``
847       domain is only used for JavaScript translation catalogs to make sure
848       that those are as small as possible.
849     * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
850       ``xgettext`` and ``msgfmt``. This is mostly for convenience.