5 Django has full support for internationalization of text in code and templates.
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
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
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
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.
71 Specify a translation string by using the function ``ugettext()``. It's
72 convention to import this as a shorter alias, ``_``, to save typing.
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
93 from django.utils.translation import ugettext as _
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
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.'
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
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.
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``
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'))
193 verbose_name = _('my thing')
194 verbose_name_plural = _('mythings')
196 .. _Django models: ../model-api/
201 Use the function ``django.utils.translation.ungettext()`` to specify pluralized
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) % {
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).
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
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
242 {% blocktrans with value|filter as myvar %}
243 This will have {{ myvar }} inside.
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 }}
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.
260 There are {{ counter }} {{ name }} objects.
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
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.
296 In this example, the translation infrastructure will be passed the string
297 ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
298 translated string will need to contain the comma so that the filter
299 parsing code knows how to split up the arguments. For example, a German
300 translator might translate the string ``"yes,no"`` as ``"ja,nein"``
301 (keeping the comma intact).
303 .. _Django templates: ../templates_python/
305 Working with lazy translation objects
306 -------------------------------------
308 Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
309 and utility functions is a common operation. When you're working with these
310 objects elsewhere in your code, you should ensure that you don't accidentally
311 convert them to strings, because they should be converted as late as possible
312 (so that the correct locale is in effect). This necessitates the use of a
313 couple of helper functions.
315 Joining strings: string_concat()
316 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
318 Standard Python string joins (``''.join([...])``) will not work on lists
319 containing lazy translation objects. Instead, you can use
320 ``django.utils.translation.string_concat()``, which creates a lazy object that
321 concatenates its contents *and* converts them to strings only when the result
322 is included in a string. For example::
324 from django.utils.translation import string_concat
326 name = ugettext_lazy(u'John Lennon')
327 instrument = ugettext_lazy(u'guitar')
328 result = string_concat([name, ': ', instrument])
330 In this case, the lazy translations in ``result`` will only be converted to
331 strings when ``result`` itself is used in a string (usually at template
334 The allow_lazy() decorator
335 ~~~~~~~~~~~~~~~~~~~~~~~~~~
337 Django offers many utility functions (particularly in ``django.utils``) that
338 take a string as their first argument and do something to that string. These
339 functions are used by template filters as well as directly in other code.
341 If you write your own similar functions and deal with translations, you'll
342 face the problem of what to do when the first argument is a lazy translation
343 object. You don't want to convert it to a string immediately, because you might
344 be using this function outside of a view (and hence the current thread's locale
345 setting will not be correct).
347 For cases like this, use the ``django.utils.functional.allow_lazy()``
348 decorator. It modifies the function so that *if* it's called with a lazy
349 translation as the first argument, the function evaluation is delayed until it
350 needs to be converted to a string.
354 from django.utils.functional import allow_lazy
356 def fancy_utility_function(s, ...):
357 # Do some conversion on string 's'
359 fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
361 The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
362 a number of extra arguments (``*args``) specifying the type(s) that the
363 original function can return. Usually, it's enough to include ``unicode`` here
364 and ensure that your function returns only Unicode strings.
366 Using this decorator means you can write your function and assume that the
367 input is a proper string, then add support for lazy translation objects at the
370 2. How to create language files
371 ===============================
373 Once you've tagged your strings for later translation, you need to write (or
374 obtain) the language translations themselves. Here's how that works.
376 .. admonition:: Locale restrictions
378 Django does not support localizing your application into a locale for
379 which Django itself has not been translated. In this case, it will ignore
380 your translation files. If you were to try this and Django supported it,
381 you would inevitably see a mixture of translated strings (from your
382 application) and English strings (from Django itself). If you want to
383 support a locale for your application that is not already part of
384 Django, you'll need to make at least a minimal translation of the Django
390 The first step is to create a **message file** for a new language. A message
391 file is a plain-text file, representing a single language, that contains all
392 available translation strings and how they should be represented in the given
393 language. Message files have a ``.po`` file extension.
395 Django comes with a tool, ``bin/make-messages.py``, that automates the creation
396 and upkeep of these files.
398 To create or update a message file, run this command::
400 bin/make-messages.py -l de
402 ...where ``de`` is the language code for the message file you want to create.
403 The language code, in this case, is in locale format. For example, it's
404 ``pt_BR`` for Brazilian Portuguese and ``de_AT`` for Austrian German.
406 The script should be run from one of three places:
408 * The root ``django`` directory (not a Subversion checkout, but the one
409 that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
411 * The root directory of your Django project.
412 * The root directory of your Django app.
414 The script runs over the entire Django source tree and pulls out all strings
415 marked for translation. It creates (or updates) a message file in the directory
416 ``conf/locale``. In the ``de`` example, the file will be
417 ``conf/locale/de/LC_MESSAGES/django.po``.
419 If run over your project source tree or your application source tree, it will
420 do the same, but the location of the locale directory is ``locale/LANG/LC_MESSAGES``
421 (note the missing ``conf`` prefix).
423 .. admonition:: No gettext?
425 If you don't have the ``gettext`` utilities installed, ``make-messages.py``
426 will create empty files. If that's the case, either install the ``gettext``
427 utilities or just copy the English message file
428 (``conf/locale/en/LC_MESSAGES/django.po``) and use it as a starting point;
429 it's just an empty translation file.
431 The format of ``.po`` files is straightforward. Each ``.po`` file contains a
432 small bit of metadata, such as the translation maintainer's contact
433 information, but the bulk of the file is a list of **messages** -- simple
434 mappings between translation strings and the actual translated text for the
437 For example, if your Django app contained a translation string for the text
438 ``"Welcome to my site."``, like so::
440 _("Welcome to my site.")
442 ...then ``make-messages.py`` will have created a ``.po`` file containing the
443 following snippet -- a message::
445 #: path/to/python/module.py:23
446 msgid "Welcome to my site."
451 * ``msgid`` is the translation string, which appears in the source. Don't
453 * ``msgstr`` is where you put the language-specific translation. It starts
454 out empty, so it's your responsibility to change it. Make sure you keep
455 the quotes around your translation.
456 * As a convenience, each message includes the filename and line number
457 from which the translation string was gleaned.
459 Long messages are a special case. There, the first string directly after the
460 ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
461 written over the next few lines as one string per line. Those strings are
462 directly concatenated. Don't forget trailing spaces within the strings;
463 otherwise, they'll be tacked together without whitespace!
465 .. admonition:: Mind your charset
467 When creating a PO file with your favorite text editor, first edit
468 the charset line (search for ``"CHARSET"``) and set it to the charset
469 you'll be using to edit the content. Due to the way the ``gettext`` tools
470 work internally and because we want to allow non-ASCII source strings in
471 Django's core and your applications, you **must** use UTF-8 as the encoding
472 for your PO file. This means that everybody will be using the same
473 encoding, which is important when Django processes the PO files.
475 To reexamine all source code and templates for new translation strings and
476 update all message files for **all** languages, run this::
480 Compiling message files
481 -----------------------
483 After you create your message file -- and each time you make changes to it --
484 you'll need to compile it into a more efficient form, for use by ``gettext``.
485 Do this with the ``bin/compile-messages.py`` utility.
487 This tool runs over all available ``.po`` files and creates ``.mo`` files,
488 which are binary files optimized for use by ``gettext``. In the same directory
489 from which you ran ``make-messages.py``, run ``compile-messages.py`` like
492 bin/compile-messages.py
494 That's it. Your translations are ready for use.
496 .. admonition:: A note to translators
498 If you've created a translation in a language Django doesn't yet support,
499 please let us know! See `Submitting and maintaining translations`_ for
502 .. _Submitting and maintaining translations: ../contributing/
504 3. How Django discovers language preference
505 ===========================================
507 Once you've prepared your translations -- or, if you just want to use the
508 translations that come with Django -- you'll just need to activate translation
511 Behind the scenes, Django has a very flexible model of deciding which language
512 should be used -- installation-wide, for a particular user, or both.
514 To set an installation-wide language preference, set ``LANGUAGE_CODE`` in your
515 `settings file`_. Django uses this language as the default translation -- the
516 final attempt if no other translator finds a translation.
518 If all you want to do is run Django with your native language, and a language
519 file is available for your language, all you need to do is set
522 If you want to let each individual user specify which language he or she
523 prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
524 selection based on data from the request. It customizes content for each user.
526 To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
527 to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
528 should follow these guidelines:
530 * Make sure it's one of the first middlewares installed.
531 * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
532 makes use of session data.
533 * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
535 For example, your ``MIDDLEWARE_CLASSES`` might look like this::
537 MIDDLEWARE_CLASSES = (
538 'django.contrib.sessions.middleware.SessionMiddleware',
539 'django.middleware.locale.LocaleMiddleware',
540 'django.middleware.common.CommonMiddleware',
543 (For more on middleware, see the `middleware documentation`_.)
545 ``LocaleMiddleware`` tries to determine the user's language preference by
546 following this algorithm:
548 * First, it looks for a ``django_language`` key in the the current user's
550 * 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``.)
551 * Failing that, it looks at the ``Accept-Language`` HTTP header. This
552 header is sent by your browser and tells the server which language(s) you
553 prefer, in order by priority. Django tries each language in the header
554 until it finds one with available translations.
555 * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
559 * In each of these places, the language preference is expected to be in the
560 standard language format, as a string. For example, Brazilian Portuguese
562 * If a base language is available but the sublanguage specified is not,
563 Django uses the base language. For example, if a user specifies ``de-at``
564 (Austrian German) but Django only has ``de`` available, Django uses
566 * Only languages listed in the `LANGUAGES setting`_ can be selected. If
567 you want to restrict the language selection to a subset of provided
568 languages (because your application doesn't provide all those languages),
569 set ``LANGUAGES`` to a list of languages. For example::
573 ('en', _('English')),
576 This example restricts languages that are available for automatic
577 selection to German and English (and any sublanguage, like de-ch or
580 .. _LANGUAGES setting: ../settings/#languages
582 * If you define a custom ``LANGUAGES`` setting, as explained in the
583 previous bullet, it's OK to mark the languages as translation strings
584 -- but use a "dummy" ``ugettext()`` function, not the one in
585 ``django.utils.translation``. You should *never* import
586 ``django.utils.translation`` from within your settings file, because that
587 module in itself depends on the settings, and that would cause a circular
590 The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
593 ugettext = lambda s: s
596 ('de', ugettext('German')),
597 ('en', ugettext('English')),
600 With this arrangement, ``make-messages.py`` will still find and mark
601 these strings for translation, but the translation won't happen at
602 runtime -- so you'll have to remember to wrap the languages in the *real*
603 ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
605 * The ``LocaleMiddleware`` can only select languages for which there is a
606 Django-provided base translation. If you want to provide translations
607 for your application that aren't already in the set of translations
608 in Django's source tree, you'll want to provide at least basic
609 translations for that language. For example, Django uses technical
610 message IDs to translate date formats and time formats -- so you will
611 need at least those translations for the system to work correctly.
613 A good starting point is to copy the English ``.po`` file and to
614 translate at least the technical messages -- maybe the validator
617 Technical message IDs are easily recognized; they're all upper case. You
618 don't translate the message ID as with other messages, you provide the
619 correct local variant on the provided English value. For example, with
620 ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
621 be the format string that you want to use in your language. The format
622 is identical to the format strings used by the ``now`` template tag.
624 Once ``LocaleMiddleware`` determines the user's preference, it makes this
625 preference available as ``request.LANGUAGE_CODE`` for each `request object`_.
626 Feel free to read this value in your view code. Here's a simple example::
628 def hello_world(request, count):
629 if request.LANGUAGE_CODE == 'de-at':
630 return HttpResponse("You prefer to read Austrian German.")
632 return HttpResponse("You prefer to read another language.")
634 Note that, with static (middleware-less) translation, the language is in
635 ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
636 in ``request.LANGUAGE_CODE``.
638 .. _settings file: ../settings/
639 .. _middleware documentation: ../middleware/
640 .. _session: ../sessions/
641 .. _request object: ../request_response/#httprequest-objects
643 Using translations in your own projects
644 =======================================
646 Django looks for translations by following this algorithm:
648 * First, it looks for a ``locale`` directory in the application directory
649 of the view that's being called. If it finds a translation for the
650 selected language, the translation will be installed.
651 * Next, it looks for a ``locale`` directory in the project directory. If it
652 finds a translation, the translation will be installed.
653 * Finally, it checks the base translation in ``django/conf/locale``.
655 This way, you can write applications that include their own translations, and
656 you can override base translations in your project path. Or, you can just build
657 a big project out of several apps and put all translations into one big project
658 message file. The choice is yours.
662 If you're using manually configured settings, as described in the
663 `settings documentation`_, the ``locale`` directory in the project
664 directory will not be examined, since Django loses the ability to work out
665 the location of the project directory. (Django normally uses the location
666 of the settings file to determine this, and a settings file doesn't exist
667 if you're manually configuring your settings.)
669 .. _settings documentation: ../settings/#using-settings-without-setting-django-settings-module
671 All message file repositories are structured the same way. They are:
673 * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
674 * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
675 * All paths listed in ``LOCALE_PATHS`` in your settings file are
676 searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
677 * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
679 To create message files, you use the same ``make-messages.py`` tool as with the
680 Django message files. You only need to be in the right place -- in the directory
681 where either the ``conf/locale`` (in case of the source tree) or the ``locale/``
682 (in case of app messages or project messages) directory are located. And you
683 use the same ``compile-messages.py`` to produce the binary ``django.mo`` files
684 that are used by ``gettext``.
686 You can also run ``compile-message.py --settings=path.to.settings`` to make
687 the compiler process all the directories in your ``LOCALE_PATHS`` setting.
689 Application message files are a bit complicated to discover -- they need the
690 ``LocaleMiddleware``. If you don't use the middleware, only the Django message
691 files and project message files will be processed.
693 Finally, you should give some thought to the structure of your translation
694 files. If your applications need to be delivered to other users and will
695 be used in other projects, you might want to use app-specific translations.
696 But using app-specific translations and project translations could produce
697 weird problems with ``make-messages``: ``make-messages`` will traverse all
698 directories below the current path and so might put message IDs into the
699 project message file that are already in application message files.
701 The easiest way out is to store applications that are not part of the project
702 (and so carry their own translations) outside the project tree. That way,
703 ``make-messages`` on the project level will only translate strings that are
704 connected to your explicit project and not strings that are distributed
707 The ``set_language`` redirect view
708 ==================================
710 As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
711 that sets a user's language preference and redirects back to the previous page.
713 Activate this view by adding the following line to your URLconf::
715 (r'^i18n/', include('django.conf.urls.i18n')),
717 (Note that this example makes the view available at ``/i18n/setlang/``.)
719 The view expects to be called via the ``POST`` method, with a ``language``
720 parameter set in request. If session support is enabled, the view
721 saves the language choice in the user's session. Otherwise, it saves the
722 language choice in a cookie that is by default named ``django_language``.
723 (The name can be changed through the ``LANGUAGE_COOKIE_NAME`` setting if you're
724 using the Django development version.)
726 After setting the language choice, Django redirects the user, following this
729 * Django looks for a ``next`` parameter in the ``POST`` data.
730 * If that doesn't exist, or is empty, Django tries the URL in the
732 * If that's empty -- say, if a user's browser suppresses that header --
733 then the user will be redirected to ``/`` (the site root) as a fallback.
735 Here's example HTML template code::
737 <form action="/i18n/setlang/" method="post">
738 <input name="next" type="hidden" value="/next/page/" />
739 <select name="language">
740 {% for lang in LANGUAGES %}
741 <option value="{{ lang.0 }}">{{ lang.1 }}</option>
744 <input type="submit" value="Go" />
747 Translations and JavaScript
748 ===========================
750 Adding translations to JavaScript poses some problems:
752 * JavaScript code doesn't have access to a ``gettext`` implementation.
754 * JavaScript code doesn't have access to .po or .mo files; they need to be
755 delivered by the server.
757 * The translation catalogs for JavaScript should be kept as small as
760 Django provides an integrated solution for these problems: It passes the
761 translations into JavaScript, so you can call ``gettext``, etc., from within
764 The ``javascript_catalog`` view
765 -------------------------------
767 The main solution to these problems is the ``javascript_catalog`` view, which
768 sends out a JavaScript code library with functions that mimic the ``gettext``
769 interface, plus an array of translation strings. Those translation strings are
770 taken from the application, project or Django core, according to what you
771 specify in either the info_dict or the URL.
773 You hook it up like this::
776 'packages': ('your.app.package',),
779 urlpatterns = patterns('',
780 (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
783 Each string in ``packages`` should be in Python dotted-package syntax (the
784 same format as the strings in ``INSTALLED_APPS``) and should refer to a package
785 that contains a ``locale`` directory. If you specify multiple packages, all
786 those catalogs are merged into one catalog. This is useful if you have
787 JavaScript that uses strings from different applications.
789 You can make the view dynamic by putting the packages into the URL pattern::
791 urlpatterns = patterns('',
792 (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
795 With this, you specify the packages as a list of package names delimited by '+'
796 signs in the URL. This is especially useful if your pages use code from
797 different apps and this changes often and you don't want to pull in one big
798 catalog file. As a security measure, these values can only be either
799 ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
801 Using the JavaScript translation catalog
802 ----------------------------------------
804 To use the catalog, just pull in the dynamically generated script like this::
806 <script type="text/javascript" src="/path/to/jsi18n/"></script>
808 This is how the admin fetches the translation catalog from the server. When the
809 catalog is loaded, your JavaScript code can use the standard ``gettext``
810 interface to access it::
812 document.write(gettext('this is to be translated'));
814 There is also an ``ngettext`` interface::
816 var object_cnt = 1 // or 0, or 2, or 3, ...
817 s = ngettext('literal for the singular case',
818 'literal for the plural case', object_cnt);
820 and even a string interpolation function::
822 function interpolate(fmt, obj, named);
824 The interpolation syntax is borrowed from Python, so the ``interpolate``
825 function supports both positional and named interpolation:
827 * Positional interpolation: ``obj`` contains a JavaScript Array object
828 whose elements values are then sequentially interpolated in their
829 corresponding ``fmt`` placeholders in the same order they appear.
832 fmts = ngettext('There is %s object. Remaining: %s',
833 'There are %s objects. Remaining: %s', 11);
834 s = interpolate(fmts, [11, 20]);
835 // s is 'There are 11 objects. Remaining: 20'
837 * Named interpolation: This mode is selected by passing the optional
838 boolean ``named`` parameter as true. ``obj`` contains a JavaScript
839 object or associative array. For example::
846 fmts = ngettext('Total: %(total)s, there is %(count)s object',
847 'there are %(count)s of a total of %(total)s objects', d.count);
848 s = interpolate(fmts, d, true);
850 You shouldn't go over the top with string interpolation, though: this is still
851 JavaScript, so the code has to make repeated regular-expression substitutions.
852 This isn't as fast as string interpolation in Python, so keep it to those
853 cases where you really need it (for example, in conjunction with ``ngettext``
854 to produce proper pluralizations).
856 Creating JavaScript translation catalogs
857 ----------------------------------------
859 You create and update the translation catalogs the same way as the other
860 Django translation catalogs -- with the make-messages.py tool. The only
861 difference is you need to provide a ``-d djangojs`` parameter, like this::
863 make-messages.py -d djangojs -l de
865 This would create or update the translation catalog for JavaScript for German.
866 After updating translation catalogs, just run ``compile-messages.py`` the same
867 way as you do with normal Django translation catalogs.
869 Specialties of Django translation
870 ==================================
872 If you know ``gettext``, you might note these specialties in the way Django
875 * The string domain is ``django`` or ``djangojs``. This string domain is
876 used to differentiate between different programs that store their data
877 in a common message-file library (usually ``/usr/share/locale/``). The
878 ``django`` domain is used for python and template translation strings
879 and is loaded into the global translation catalogs. The ``djangojs``
880 domain is only used for JavaScript translation catalogs to make sure
881 that those are as small as possible.
882 * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
883 ``xgettext`` and ``msgfmt``. This is mostly for convenience.