Fixed #8234: Corrected typo in docs/cache.txt
[django.git] / docs / i18n.txt
blob62d78fb22415b262028c1515b1710145e0dff781
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 ``django-admin.py makemessages``, won't be able to find these strings. More on
126 ``makemessages`` 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 (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.
278 If you don't use the ``RequestContext`` extension, you can get those values with
279 three tags::
281     {% get_current_language as LANGUAGE_CODE %}
282     {% get_available_languages as LANGUAGES %}
283     {% get_current_language_bidi as LANGUAGE_BIDI %}
285 These tags also require a ``{% load i18n %}``.
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::
291     {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
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.
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).
304 .. _Django templates: ../templates_python/
306 Working with lazy translation objects
307 -------------------------------------
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.
316 Joining strings: string_concat()
317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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::
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])
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).
335 The allow_lazy() decorator
336 ~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
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).
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.
353 For example::
355     from django.utils.functional import allow_lazy
357     def fancy_utility_function(s, ...):
358         # Do some conversion on string 's'
359         ...
360     fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
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.
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.
371 2. How to create language files
372 ===============================
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.
377 .. admonition:: Locale restrictions
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.
388 Message files
389 -------------
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.
396 Django comes with a tool, ``django-admin.py makemessages``, that automates the
397 creation and upkeep of these files. 
399 .. admonition:: A note to Django veterans
401     The old tool ``bin/make-messages.py`` has been moved to the command
402     ``django-admin.py makemessages`` to provide consistency throughout Django.
404 To create or update a message file, run this command::
406     django-admin.py makemessages -l de
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.
412 The script should be run from one of three places:
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.
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``.
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).
429 By default ``django-admin.py makemessages`` examines every file that has the
430 ``.html`` file extension. In case you want to override that default, use the
431 ``--extension`` or ``-e`` option to specify the file extensions to examine::
433     django-admin.py makemessages -l de -e txt
435 Separate multiple extensions with commas and/or use ``-e`` or ``--extension`` multiple times::
437     django-admin.py makemessages -l=de -e=html,txt -e xml
439 When `creating JavaScript translation catalogs`_ you need to use the special
440 'djangojs' domain, **not** ``-e js``.
442 .. _create a JavaScript translation catalog: #creating-javascript-translation-catalogs
444 .. admonition:: No gettext?
446     If you don't have the ``gettext`` utilities installed,
447     ``django-admin.py makemessages`` will create empty files. If that's the
448     case, either install the ``gettext`` utilities or just copy the English
449     message file (``conf/locale/en/LC_MESSAGES/django.po``) and use it as a
450     starting point; it's just an empty translation file.
452 .. admonition:: Working on Windows?
454    If you're using Windows and need to install the GNU gettext utilites so
455    ``django-admin makemessages`` works see `gettext on Windows`_ for more
456    information.
458 The format of ``.po`` files is straightforward. Each ``.po`` file contains a
459 small bit of metadata, such as the translation maintainer's contact
460 information, but the bulk of the file is a list of **messages** -- simple
461 mappings between translation strings and the actual translated text for the
462 particular language.
464 For example, if your Django app contained a translation string for the text
465 ``"Welcome to my site."``, like so::
467     _("Welcome to my site.")
469 ...then ``django-admin.py makemessages`` will have created a ``.po`` file
470 containing the following snippet -- a message::
472     #: path/to/python/module.py:23
473     msgid "Welcome to my site."
474     msgstr ""
476 A quick explanation:
478     * ``msgid`` is the translation string, which appears in the source. Don't
479       change it.
480     * ``msgstr`` is where you put the language-specific translation. It starts
481       out empty, so it's your responsibility to change it. Make sure you keep
482       the quotes around your translation.
483     * As a convenience, each message includes the filename and line number
484       from which the translation string was gleaned.
486 Long messages are a special case. There, the first string directly after the
487 ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
488 written over the next few lines as one string per line. Those strings are
489 directly concatenated. Don't forget trailing spaces within the strings;
490 otherwise, they'll be tacked together without whitespace!
492 .. admonition:: Mind your charset
494     When creating a PO file with your favorite text editor, first edit
495     the charset line (search for ``"CHARSET"``) and set it to the charset
496     you'll be using to edit the content. Due to the way the ``gettext`` tools
497     work internally and because we want to allow non-ASCII source strings in
498     Django's core and your applications, you **must** use UTF-8 as the encoding
499     for your PO file. This means that everybody will be using the same
500     encoding, which is important when Django processes the PO files.
502 To reexamine all source code and templates for new translation strings and
503 update all message files for **all** languages, run this::
505     django-admin.py makemessages -a
507 Compiling message files
508 -----------------------
510 After you create your message file -- and each time you make changes to it --
511 you'll need to compile it into a more efficient form, for use by ``gettext``.
512 Do this with the ``django-admin.py compilemessages`` utility.
514 This tool runs over all available ``.po`` files and creates ``.mo`` files,
515 which are binary files optimized for use by ``gettext``. In the same directory
516 from which you ran ``django-admin.py makemessages``, run
517 ``django-admin.py compilemessages`` like this::
519    django-admin.py compilemessages
521 That's it. Your translations are ready for use.
523 .. admonition:: A note to Django veterans
525     The old tool ``bin/compile-messages.py`` has been moved to the command
526     ``django-admin.py compilemessages`` to provide consistency throughout
527     Django.
529 .. admonition:: A note to translators
531     If you've created a translation in a language Django doesn't yet support,
532     please let us know! See `Submitting and maintaining translations`_ for
533     the steps to take.
535     .. _Submitting and maintaining translations: ../contributing/
537 .. admonition:: Working on Windows?
539    If you're using Windows and need to install the GNU gettext utilites so
540    ``django-admin compilemessages`` works see `gettext on Windows`_ for more
541    information.
543 3. How Django discovers language preference
544 ===========================================
546 Once you've prepared your translations -- or, if you just want to use the
547 translations that come with Django -- you'll just need to activate translation
548 for your app.
550 Behind the scenes, Django has a very flexible model of deciding which language
551 should be used -- installation-wide, for a particular user, or both.
553 To set an installation-wide language preference, set ``LANGUAGE_CODE`` in your
554 `settings file`_. Django uses this language as the default translation -- the
555 final attempt if no other translator finds a translation.
557 If all you want to do is run Django with your native language, and a language
558 file is available for your language, all you need to do is set
559 ``LANGUAGE_CODE``.
561 If you want to let each individual user specify which language he or she
562 prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
563 selection based on data from the request. It customizes content for each user.
565 To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
566 to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
567 should follow these guidelines:
569     * Make sure it's one of the first middlewares installed.
570     * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
571       makes use of session data.
572     * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
574 For example, your ``MIDDLEWARE_CLASSES`` might look like this::
576     MIDDLEWARE_CLASSES = (
577        'django.contrib.sessions.middleware.SessionMiddleware',
578        'django.middleware.locale.LocaleMiddleware',
579        'django.middleware.common.CommonMiddleware',
580     )
582 (For more on middleware, see the `middleware documentation`_.)
584 ``LocaleMiddleware`` tries to determine the user's language preference by
585 following this algorithm:
587     * First, it looks for a ``django_language`` key in the the current user's
588       `session`_.
589     * 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``.)
590     * Failing that, it looks at the ``Accept-Language`` HTTP header. This
591       header is sent by your browser and tells the server which language(s) you
592       prefer, in order by priority. Django tries each language in the header
593       until it finds one with available translations.
594     * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
596 Notes:
598     * In each of these places, the language preference is expected to be in the
599       standard language format, as a string. For example, Brazilian Portuguese
600       is ``pt-br``.
601     * If a base language is available but the sublanguage specified is not,
602       Django uses the base language. For example, if a user specifies ``de-at``
603       (Austrian German) but Django only has ``de`` available, Django uses
604       ``de``.
605     * Only languages listed in the `LANGUAGES setting`_ can be selected. If
606       you want to restrict the language selection to a subset of provided
607       languages (because your application doesn't provide all those languages),
608       set ``LANGUAGES`` to a list of languages. For example::
610           LANGUAGES = (
611             ('de', _('German')),
612             ('en', _('English')),
613           )
615       This example restricts languages that are available for automatic
616       selection to German and English (and any sublanguage, like de-ch or
617       en-us).
619       .. _LANGUAGES setting: ../settings/#languages
621     * If you define a custom ``LANGUAGES`` setting, as explained in the
622       previous bullet, it's OK to mark the languages as translation strings
623       -- but use a "dummy" ``ugettext()`` function, not the one in
624       ``django.utils.translation``. You should *never* import
625       ``django.utils.translation`` from within your settings file, because that
626       module in itself depends on the settings, and that would cause a circular
627       import.
629       The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
630       settings file::
632           ugettext = lambda s: s
634           LANGUAGES = (
635               ('de', ugettext('German')),
636               ('en', ugettext('English')),
637           )
639       With this arrangement, ``django-admin.py makemessages`` will still find
640       and mark these strings for translation, but the translation won't happen
641       at runtime -- so you'll have to remember to wrap the languages in the *real*
642       ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
644     * The ``LocaleMiddleware`` can only select languages for which there is a
645       Django-provided base translation. If you want to provide translations
646       for your application that aren't already in the set of translations
647       in Django's source tree, you'll want to provide at least basic
648       translations for that language. For example, Django uses technical
649       message IDs to translate date formats and time formats -- so you will
650       need at least those translations for the system to work correctly.
652       A good starting point is to copy the English ``.po`` file and to
653       translate at least the technical messages -- maybe the validator
654       messages, too.
656       Technical message IDs are easily recognized; they're all upper case. You
657       don't translate the message ID as with other messages, you provide the
658       correct local variant on the provided English value. For example, with
659       ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
660       be the format string that you want to use in your language. The format
661       is identical to the format strings used by the ``now`` template tag.
663 Once ``LocaleMiddleware`` determines the user's preference, it makes this
664 preference available as ``request.LANGUAGE_CODE`` for each `request object`_.
665 Feel free to read this value in your view code. Here's a simple example::
667     def hello_world(request, count):
668         if request.LANGUAGE_CODE == 'de-at':
669             return HttpResponse("You prefer to read Austrian German.")
670         else:
671             return HttpResponse("You prefer to read another language.")
673 Note that, with static (middleware-less) translation, the language is in
674 ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
675 in ``request.LANGUAGE_CODE``.
677 .. _settings file: ../settings/
678 .. _middleware documentation: ../middleware/
679 .. _session: ../sessions/
680 .. _request object: ../request_response/#httprequest-objects
682 Using translations in your own projects
683 =======================================
685 Django looks for translations by following this algorithm:
687     * First, it looks for a ``locale`` directory in the application directory
688       of the view that's being called. If it finds a translation for the
689       selected language, the translation will be installed.
690     * Next, it looks for a ``locale`` directory in the project directory. If it
691       finds a translation, the translation will be installed.
692     * Finally, it checks the base translation in ``django/conf/locale``.
694 This way, you can write applications that include their own translations, and
695 you can override base translations in your project path. Or, you can just build
696 a big project out of several apps and put all translations into one big project
697 message file. The choice is yours.
699 .. note::
701     If you're using manually configured settings, as described in the
702     `settings documentation`_, the ``locale`` directory in the project
703     directory will not be examined, since Django loses the ability to work out
704     the location of the project directory. (Django normally uses the location
705     of the settings file to determine this, and a settings file doesn't exist
706     if you're manually configuring your settings.)
708 .. _settings documentation: ../settings/#using-settings-without-setting-django-settings-module
710 All message file repositories are structured the same way. They are:
712     * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
713     * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
714     * All paths listed in ``LOCALE_PATHS`` in your settings file are
715       searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
716     * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
718 To create message files, you use the same ``django-admin.py makemessages``
719 tool as with the Django message files. You only need to be in the right place
720 -- in the directory where either the ``conf/locale`` (in case of the source
721 tree) or the ``locale/`` (in case of app messages or project messages)
722 directory are located. And you use the same ``django-admin.py compilemessages``
723 to produce the binary ``django.mo`` files that are used by ``gettext``.
725 You can also run ``django-admin.py compilemessages --settings=path.to.settings``
726 to make the compiler process all the directories in your ``LOCALE_PATHS``
727 setting.
729 Application message files are a bit complicated to discover -- they need the
730 ``LocaleMiddleware``. If you don't use the middleware, only the Django message
731 files and project message files will be processed.
733 Finally, you should give some thought to the structure of your translation
734 files. If your applications need to be delivered to other users and will
735 be used in other projects, you might want to use app-specific translations.
736 But using app-specific translations and project translations could produce
737 weird problems with ``makemessages``: ``makemessages`` will traverse all
738 directories below the current path and so might put message IDs into the
739 project message file that are already in application message files.
741 The easiest way out is to store applications that are not part of the project
742 (and so carry their own translations) outside the project tree. That way,
743 ``django-admin.py makemessages`` on the project level will only translate
744 strings that are connected to your explicit project and not strings that are
745 distributed independently.
747 The ``set_language`` redirect view
748 ==================================
750 As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
751 that sets a user's language preference and redirects back to the previous page.
753 Activate this view by adding the following line to your URLconf::
755     (r'^i18n/', include('django.conf.urls.i18n')),
757 (Note that this example makes the view available at ``/i18n/setlang/``.)
759 The view expects to be called via the ``POST`` method, with a ``language``
760 parameter set in request. If session support is enabled, the view
761 saves the language choice in the user's session. Otherwise, it saves the
762 language choice in a cookie that is by default named ``django_language``.
763 (The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting if you're
764 using the Django development version.)
766 After setting the language choice, Django redirects the user, following this
767 algorithm:
769     * Django looks for a ``next`` parameter in the ``POST`` data.
770     * If that doesn't exist, or is empty, Django tries the URL in the
771       ``Referrer`` header.
772     * If that's empty -- say, if a user's browser suppresses that header --
773       then the user will be redirected to ``/`` (the site root) as a fallback.
775 Here's example HTML template code::
777     <form action="/i18n/setlang/" method="post">
778     <input name="next" type="hidden" value="/next/page/" />
779     <select name="language">
780     {% for lang in LANGUAGES %}
781     <option value="{{ lang.0 }}">{{ lang.1 }}</option>
782     {% endfor %}
783     </select>
784     <input type="submit" value="Go" />
785     </form>
787 Translations and JavaScript
788 ===========================
790 Adding translations to JavaScript poses some problems:
792     * JavaScript code doesn't have access to a ``gettext`` implementation.
794     * JavaScript code doesn't have access to .po or .mo files; they need to be
795       delivered by the server.
797     * The translation catalogs for JavaScript should be kept as small as
798       possible.
800 Django provides an integrated solution for these problems: It passes the
801 translations into JavaScript, so you can call ``gettext``, etc., from within
802 JavaScript.
804 The ``javascript_catalog`` view
805 -------------------------------
807 The main solution to these problems is the ``javascript_catalog`` view, which
808 sends out a JavaScript code library with functions that mimic the ``gettext``
809 interface, plus an array of translation strings. Those translation strings are
810 taken from the application, project or Django core, according to what you
811 specify in either the info_dict or the URL.
813 You hook it up like this::
815     js_info_dict = {
816         'packages': ('your.app.package',),
817     }
819     urlpatterns = patterns('',
820         (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
821     )
823 Each string in ``packages`` should be in Python dotted-package syntax (the
824 same format as the strings in ``INSTALLED_APPS``) and should refer to a package
825 that contains a ``locale`` directory. If you specify multiple packages, all
826 those catalogs are merged into one catalog. This is useful if you have
827 JavaScript that uses strings from different applications.
829 You can make the view dynamic by putting the packages into the URL pattern::
831     urlpatterns = patterns('',
832         (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
833     )
835 With this, you specify the packages as a list of package names delimited by '+'
836 signs in the URL. This is especially useful if your pages use code from
837 different apps and this changes often and you don't want to pull in one big
838 catalog file. As a security measure, these values can only be either
839 ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
841 Using the JavaScript translation catalog
842 ----------------------------------------
844 To use the catalog, just pull in the dynamically generated script like this::
846     <script type="text/javascript" src="/path/to/jsi18n/"></script>
848 This is how the admin fetches the translation catalog from the server. When the
849 catalog is loaded, your JavaScript code can use the standard ``gettext``
850 interface to access it::
852     document.write(gettext('this is to be translated'));
854 There is also an ``ngettext`` interface::
856     var object_cnt = 1 // or 0, or 2, or 3, ...
857     s = ngettext('literal for the singular case',
858             'literal for the plural case', object_cnt);
860 and even a string interpolation function::
862     function interpolate(fmt, obj, named);
864 The interpolation syntax is borrowed from Python, so the ``interpolate``
865 function supports both positional and named interpolation:
867     * Positional interpolation: ``obj`` contains a JavaScript Array object
868       whose elements values are then sequentially interpolated in their
869       corresponding ``fmt`` placeholders in the same order they appear.
870       For example::
872         fmts = ngettext('There is %s object. Remaining: %s',
873                 'There are %s objects. Remaining: %s', 11);
874         s = interpolate(fmts, [11, 20]);
875         // s is 'There are 11 objects. Remaining: 20'
877     * Named interpolation: This mode is selected by passing the optional
878       boolean ``named`` parameter as true. ``obj`` contains a JavaScript
879       object or associative array. For example::
881         d = {
882             count: 10
883             total: 50
884         };
886         fmts = ngettext('Total: %(total)s, there is %(count)s object',
887         'there are %(count)s of a total of %(total)s objects', d.count);
888         s = interpolate(fmts, d, true);
890 You shouldn't go over the top with string interpolation, though: this is still
891 JavaScript, so the code has to make repeated regular-expression substitutions.
892 This isn't as fast as string interpolation in Python, so keep it to those
893 cases where you really need it (for example, in conjunction with ``ngettext``
894 to produce proper pluralizations).
896 Creating JavaScript translation catalogs
897 ----------------------------------------
899 You create and update the translation catalogs the same way as the other
900 Django translation catalogs -- with the django-admin.py makemessages tool. The
901 only difference is you need to provide a ``-d djangojs`` parameter, like this::
903     django-admin.py makemessages -d djangojs -l de
905 This would create or update the translation catalog for JavaScript for German.
906 After updating translation catalogs, just run ``django-admin.py compilemessages``
907 the same way as you do with normal Django translation catalogs.
909 Specialties of Django translation
910 ==================================
912 If you know ``gettext``, you might note these specialties in the way Django
913 does translation:
915     * The string domain is ``django`` or ``djangojs``. This string domain is
916       used to differentiate between different programs that store their data
917       in a common message-file library (usually ``/usr/share/locale/``). The
918       ``django`` domain is used for Python and template translation strings
919       and is loaded into the global translation catalogs. The ``djangojs``
920       domain is only used for JavaScript translation catalogs to make sure
921       that those are as small as possible.
922     * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
923       ``xgettext`` and ``msgfmt``. This is mostly for convenience.
925 ``gettext`` on Windows
926 ======================
928 This is only needed for people who either want to extract message IDs or
929 compile ``.po`` files. Translation work itself just involves editing existing
930 ``.po`` files, but if you want to create your own .po files, or want to test
931 or compile a changed ``.po`` file, you will need the ``gettext`` utilities:
933     * Download the following zip files from http://sourceforge.net/projects/gettext
935       * ``gettext-runtime-X.bin.woe32.zip``
936       * ``gettext-tools-X.bin.woe32.zip``
937       * ``libiconv-X.bin.woe32.zip``
939     * Extract the 3 files in the same folder (i.e. ``C:\Program Files\gettext-utils``)
941     * Update the system PATH:
943       * ``Control Panel > System > Advanced > Environment Variables``
944       * In the ``System variables`` list, click ``Path``, click ``Edit``
945       * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the ``Variable value``