Translation

Overview

In order to make a Django project translatable, you have to add a minimal number of hooks to your Python code and templates. These hooks are called translation strings. They tell Django: “This text should be translated into the end user’s language, if a translation for this text is available in that language.” It’s your responsibility to mark translatable strings; the system can only translate strings it knows about.

Django then provides utilities to extract the translation strings into a message file. This file is a convenient way for translators to provide the equivalent of the translation strings in the target language. Once the translators have filled in the message file, it must be compiled. This process relies on the GNU gettext toolset.

Once this is done, Django takes care of translating Web apps on the fly in each available language, according to users’ language preferences.

Django’s internationalization hooks are on by default, and that means there’s a bit of i18n-related overhead in certain places of the framework. If you don’t use internationalization, you should take the two seconds to set USE_I18N = False in your settings file. Then Django will make some optimizations so as not to load the internationalization machinery.

Note

There is also an independent but related USE_L10N setting that controls if Django should implement format localization. See Format localization for more details.


Note

Make sure you’ve activated translation for your project (the fastest way is to check if MIDDLEWARE includes django.middleware.locale.LocaleMiddleware). If you haven’t yet, see How Django discovers language preference.


Internationalization: in Python code

Standard translation

Specify a translation string by using the function gettext(). It’s convention to import this as a shorter alias, _, to save typing.

Note

Python’s standard library gettext module installs _() into the global namespace, as an alias for gettext(). In Django, we have chosen not to follow this practice, for a couple of reasons:

  1. Sometimes, you should use gettext_lazy() as the default translation method for a particular file. Without _() in the global namespace, the developer has to think about which is the most appropriate translation function.
  2. The underscore character (_) is used to represent “the previous result” in Python’s interactive shell and doctest tests. Installing a global _() function causes interference. Explicitly importing gettext() as _() avoids this problem.


What functions may be aliased as _?

Because of how xgettext (used by makemessages) works, only functions that take a single string argument can be imported as _:


In this example, the text "Welcome to my site." is marked as a translation string:

from django.http import HttpResponse
from django.utils.translation import gettext as _

def my_view(request):
    output = _("Welcome to my site.")
    return HttpResponse(output)

You could code this without using the alias. This example is identical to the previous one:

from django.http import HttpResponse
from django.utils.translation import gettext

def my_view(request):
    output = gettext("Welcome to my site.")
    return HttpResponse(output)

Translation works on computed values. This example is identical to the previous two:

def my_view(request):
    words = ['Welcome', 'to', 'my', 'site.']
    output = _(' '.join(words))
    return HttpResponse(output)

Translation works on variables. Again, here’s an identical example:

def my_view(request):
    sentence = 'Welcome to my site.'
    output = _(sentence)
    return HttpResponse(output)

(The caveat with using variables or computed values, as in the previous two examples, is that Django’s translation-string-detecting utility, django-admin makemessages, won’t be able to find these strings. More on makemessages later.)

The strings you pass to _() or gettext() can take placeholders, specified with Python’s standard named-string interpolation syntax. Example:

def my_view(request, m, d):
    output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
    return HttpResponse(output)

This technique lets language-specific translations reorder the placeholder text. For example, an English translation may be "Today is November 26.", while a Spanish translation may be "Hoy es 26 de noviembre." – with the month and the day placeholders swapped.

For this reason, you should use named-string interpolation (e.g., %(day)s) instead of positional interpolation (e.g., %s or %d) whenever you have more than a single parameter. If you used positional interpolation, translations wouldn’t be able to reorder placeholder text.

Since string extraction is done by the xgettext command, only syntaxes supported by gettext are supported by Django. In particular, Python f-strings are not yet supported by xgettext, and JavaScript template strings need gettext 0.21+.


Comments for translators

If you would like to give translators hints about a translatable string, you can add a comment prefixed with the Translators keyword on the line preceding the string, e.g.:

def my_view(request):
    # Translators: This message appears on the home page only
    output = gettext("Welcome to my site.")

The comment will then appear in the resulting .po file associated with the translatable construct located below it and should also be displayed by most translation tools.

Note

Just for completeness, this is the corresponding fragment of the resulting .po file:

#. Translators: This message appears on the home page only
# path/to/python/file.py:123
msgid "Welcome to my site."
msgstr ""

This also works in templates. See Comments for translators in templates for more details.


Marking strings as no-op

Use the function django.utils.translation.gettext_noop() to mark a string as a translation string without translating it. The string is later translated from a variable.

Use this if you have constant strings that should be stored in the source language because they are exchanged over systems or users – such as strings in a database – but should be translated at the last possible point in time, such as when the string is presented to the user.


Pluralization

Use the function django.utils.translation.ngettext() to specify pluralized messages.

ngettext() takes three arguments: the singular translation string, the plural translation string and the number of objects.

This function is useful when you need your Django application to be localizable to languages where the number and complexity of plural forms is greater than the two forms used in English (‘object’ for the singular and ‘objects’ for all the cases where count is different from one, irrespective of its value.)

For example:

from django.http import HttpResponse
from django.utils.translation import ngettext

def hello_world(request, count):
    page = ngettext(
        'there is %(count)d object',
        'there are %(count)d objects',
    count) % {
        'count': count,
    }
    return HttpResponse(page)

In this example the number of objects is passed to the translation languages as the count variable.

Note that pluralization is complicated and works differently in each language. Comparing count to 1 isn’t always the correct rule. This code looks sophisticated, but will produce incorrect results for some languages:

from django.utils.translation import ngettext
from myapp.models import Report

count = Report.objects.count()
if count == 1:
    name = Report._meta.verbose_name
else:
    name = Report._meta.verbose_name_plural

text = ngettext(
    'There is %(count)d %(name)s available.',
    'There are %(count)d %(name)s available.',
    count
) % {
    'count': count,
    'name': name
}

Don’t try to implement your own singular-or-plural logic; it won’t be correct. In a case like this, consider something like the following:

text = ngettext(
    'There is %(count)d %(name)s object available.',
    'There are %(count)d %(name)s objects available.',
    count
) % {
    'count': count,
    'name': Report._meta.verbose_name,
}

Note

When using ngettext(), make sure you use a single name for every extrapolated variable included in the literal. In the examples above, note how we used the name Python variable in both translation strings. This example, besides being incorrect in some languages as noted above, would fail:

text = ngettext(
    'There is %(count)d %(name)s available.',
    'There are %(count)d %(plural_name)s available.',
    count
) % {
    'count': Report.objects.count(),
    'name': Report._meta.verbose_name,
    'plural_name': Report._meta.verbose_name_plural
}

You would get an error when running django-admin compilemessages:

a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'

Contextual markers

Sometimes words have several meanings, such as "May" in English, which refers to a month name and to a verb. To enable translators to translate these words correctly in different contexts, you can use the django.utils.translation.pgettext() function, or the django.utils.translation.npgettext() function if the string needs pluralization. Both take a context string as the first variable.

In the resulting .po file, the string will then appear as often as there are different contextual markers for the same string (the context will appear on the msgctxt line), allowing the translator to give a different translation for each of them.

For example:

from django.utils.translation import pgettext

month = pgettext("month name", "May")

or:

from django.db import models
from django.utils.translation import pgettext_lazy

class MyThing(models.Model):
    name = models.CharField(help_text=pgettext_lazy(
        'help text for MyThing model', 'This is the help text'))

will appear in the .po file as:

msgctxt "month name"
msgid "May"
msgstr ""

Contextual markers are also supported by the trans and blocktrans template tags.


Lazy translation

Use the lazy versions of translation functions in django.utils.translation (easily recognizable by the lazy suffix in their names) to translate strings lazily – when the value is accessed rather than when they’re called.

These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering.

This is essential when calls to these functions are located in code paths that are executed at module load time.

This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases:

Model fields and relationships verbose_name and help_text option values

For example, to translate the help text of the name field in the following model, do the following:

from django.db import models
from django.utils.translation import gettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(help_text=_('This is the help text'))

You can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options:

class MyThing(models.Model):
    kind = models.ForeignKey(
        ThingKind,
        on_delete=models.CASCADE,
        related_name='kinds',
        verbose_name=_('kind'),
    )

Just like you would do in verbose_name you should provide a lowercase verbose name text for the relation as Django will automatically titlecase it when required.


Model verbose names values

It is recommended to always provide explicit verbose_name and verbose_name_plural options rather than relying on the fallback English-centric and somewhat naïve determination of verbose names Django performs by looking at the model’s class name:

from django.db import models
from django.utils.translation import gettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(_('name'), help_text=_('This is the help text'))

    class Meta:
        verbose_name = _('my thing')
        verbose_name_plural = _('my things')

Model methods short_description attribute values

For model methods, you can provide translations to Django and the admin site with the short_description attribute:

from django.db import models
from django.utils.translation import gettext_lazy as _

class MyThing(models.Model):
    kind = models.ForeignKey(
        ThingKind,
        on_delete=models.CASCADE,
        related_name='kinds',
        verbose_name=_('kind'),
    )

    def is_mouse(self):
        return self.kind.type == MOUSE_TYPE
    is_mouse.short_description = _('Is it a mouse?')

Working with lazy translation objects

The result of a gettext_lazy() call can be used wherever you would use a string (a str object) in other Django code, but it may not work with arbitrary Python code. For example, the following won’t work because the requests library doesn’t handle gettext_lazy objects:

body = gettext_lazy("I \u2764 Django")  # (unicode :heart:)
requests.post('https://example.com/send', data={'body': body})

You can avoid such problems by casting gettext_lazy() objects to text strings before passing them to non-Django code:

requests.post('https://example.com/send', data={'body': str(body)})

If you don’t like the long gettext_lazy name, you can alias it as _ (underscore), like so:

from django.db import models
from django.utils.translation import gettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(help_text=_('This is the help text'))

Using gettext_lazy() and ngettext_lazy() to mark strings in models and utility functions is a common operation. When you’re working with these objects elsewhere in your code, you should ensure that you don’t accidentally convert them to strings, because they should be converted as late as possible (so that the correct locale is in effect). This necessitates the use of the helper function described next.

Lazy translations and plural

When using lazy translation for a plural string (n[p]gettext_lazy), you generally don’t know the number argument at the time of the string definition. Therefore, you are authorized to pass a key name instead of an integer as the number argument. Then number will be looked up in the dictionary under that key during string interpolation. Here’s example:

from django import forms
from django.utils.translation import ngettext_lazy

class MyForm(forms.Form):
    error_message = ngettext_lazy("You only provided %(num)d argument",
        "You only provided %(num)d arguments", 'num')

    def clean(self):
        # ...
        if error:
            raise forms.ValidationError(self.error_message % {'num': number})

If the string contains exactly one unnamed placeholder, you can interpolate directly with the number argument:

class MyForm(forms.Form):
    error_message = ngettext_lazy(
        "You provided %d argument",
        "You provided %d arguments",
    )

    def clean(self):
        # ...
        if error:
            raise forms.ValidationError(self.error_message % number)

Formatting strings: format_lazy()

Python’s str.format() method will not work when either the format_string or any of the arguments to str.format() contains lazy translation objects. Instead, you can use django.utils.text.format_lazy(), which creates a lazy object that runs the str.format() method only when the result is included in a string. For example:

from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy
...
name = gettext_lazy('John Lennon')
instrument = gettext_lazy('guitar')
result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)

In this case, the lazy translations in result will only be converted to strings when result itself is used in a string (usually at template rendering time).


Other uses of lazy in delayed translations

For any other case where you would like to delay the translation, but have to pass the translatable string as argument to another function, you can wrap this function inside a lazy call yourself. For example:

from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

mark_safe_lazy = lazy(mark_safe, str)

And then later:

lazy_string = mark_safe_lazy(_("My string!"))

Localized names of languages

get_language_info()[source]

The get_language_info() function provides detailed information about languages:

>>> from django.utils.translation import activate, get_language_info
>>> activate('fr')
>>> li = get_language_info('de')
>>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])
German Deutsch Allemand False

The name, name_local, and name_translated attributes of the dictionary contain the name of the language in English, in the language itself, and in your current active language respectively. The bidi attribute is True only for bi-directional languages.

The source of the language information is the django.conf.locale module. Similar access to this information is available for template code. See below.


Internationalization: in template code

Translations in Django templates uses two template tags and a slightly different syntax than in Python code. To give your template access to these tags, put {% load i18n %} toward the top of your template. As with all template tags, this tag needs to be loaded in all templates which use translations, even those templates that extend from other templates which have already loaded the i18n tag.

Warning

Translated strings will not be escaped when rendered in a template. This allows you to include HTML in translations, for example for emphasis, but potentially dangerous characters (e.g. ") will also be rendered unchanged.


trans template tag

The {% trans %} template tag translates either a constant string (enclosed in single or double quotes) or variable content:

{% trans "This is the title." %}title>
<title>{% trans myvar %}title></code></pre>
</div>
</div>
<p>If the <code>noop</code> option is present, variable lookup still takes place but the translation is skipped. This is useful when “stubbing out” content that will require translation in the future:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django"><title>{% trans "myvar" noop %}title></code></pre>
</div>
</div>
<p>Internally, inline translations use an <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">gettext()</a> call.
</p><p>In case a template var (<code>myvar</code> above) is passed to the tag, the tag will first resolve such variable to a string at run-time and then look up that string in the message catalogs.
</p><p>It’s not possible to mix a template variable inside a string within <code>{% trans %}</code>. If your translations require strings with variables (placeholders), use <a href="#std-templatetag-blocktrans">{% blocktrans %}</a> instead.
</p><p>If you’d like to retrieve a translated string without displaying it, you can use the following syntax:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% trans "This is the title" as the_title %}

<title>{{ the_title }}title>
<meta name="description" content="{{ the_title }}"></code></pre>
</div>
</div>
<p>In practice you’ll use this to get a string you can use in multiple places in a template or so you can use the output as an argument for other template tags or filters:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% trans "starting point" as start %}
{% trans "end point" as end %}
{% trans "La Grande Boucle" as race %}

<h1>
  <a href="/" title="{% blocktrans %}Back to '{{ race }}' homepage{% endblocktrans %}">{{ race }}a>
h1>
<p>
{% for stage in tour_stages %}
    {% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br>{% else %}, {% endif %}
{% endfor %}
p></code></pre>
</div>
</div>
<p><code>{% trans %}</code> also supports <a href="#contextual-markers">contextual markers</a> using the <code>context</code> keyword:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% trans "May" context "month name" %}</code></pre>
</div>
</div>
</div>
<div id="blocktrans-template-tag" class="section">
<p><span id="std-templatetag-blocktrans"></span><span id="std:templatetag-blocktrans"></span>
</p>
<h3><span class="mw-headline" id="blocktrans_template_tag">blocktrans template tag</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="20">blocktrans template tag</mw:editsection></h3>
<p>Contrarily to the <a href="#std-templatetag-trans">trans</a> tag, the <code>blocktrans</code> tag allows you to mark complex sentences consisting of literals and variable content for translation by making use of placeholders:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}</code></pre>
</div>
</div>
<p>To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans with amount=article.price %}
That will cost $ {{ amount }}.
{% endblocktrans %}

{% blocktrans with myvar=value|filter %}
This will have {{ myvar }} inside.
{% endblocktrans %}</code></pre>
</div>
</div>
<p>You can use multiple expressions inside a single <code>blocktrans</code> tag:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans with book_t=book|title author_t=author|title %}
This is {{ book_t }} by {{ author_t }}
{% endblocktrans %}</code></pre>
</div>
</div>
<div class="admonition note">
<p>Note
</p><p>The previous more verbose format is still supported: <code>{% blocktrans with book|title as book_t and author|title as author_t %}</code>
</p><p><br />
</p>
</div>
<p>Other block tags (for example <code>{% for %}</code> or <code>{% if %}</code>) are not allowed inside a <code>blocktrans</code> tag.
</p><p>If resolving one of the block arguments fails, <code>blocktrans</code> will fall back to the default language by deactivating the currently active language temporarily with the <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">deactivate_all()</a> function.
</p><p>This tag also provides for pluralization. To use it:
</p>
<ul><li>Designate and bind a counter value with the name <code>count</code>. This value will be the one used to select the right plural form.</li>
<li>Specify both the singular and plural forms separating them with the <code>{% plural %}</code> tag within the <code>{% blocktrans %}</code> and <code>{% endblocktrans %}</code> tags.</li></ul>
<p>An example:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans count counter=list|length %}
There is only one {{ name }} object.
{% plural %}
There are {{ counter }} {{ name }} objects.
{% endblocktrans %}</code></pre>
</div>
</div>
<p>A more complex example:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans with amount=article.price count years=i.length %}
That will cost $ {{ amount }} per year.
{% plural %}
That will cost $ {{ amount }} per {{ years }} years.
{% endblocktrans %}</code></pre>
</div>
</div>
<p>When you use both the pluralization feature and bind values to local variables in addition to the counter value, keep in mind that the <code>blocktrans</code> construct is internally converted to an <code>ngettext</code> call. This means the same <a href="#pluralization-var-notes">notes regarding ngettext variables</a> apply.
</p><p>Reverse URL lookups cannot be carried out within the <code>blocktrans</code> and should be retrieved (and stored) beforehand:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% url 'path.to.view' arg arg2 as the_url %}
{% blocktrans %}
This is a URL: {{ the_url }}
{% endblocktrans %}</code></pre>
</div>
</div>
<p>If you’d like to retrieve a translated string without displaying it, you can use the following syntax:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans asvar the_title %}The title is {{ title }}.{% endblocktrans %}
<title>{{ the_title }}title>
<meta name="description" content="{{ the_title }}"></code></pre>
</div>
</div>
<p>In practice you’ll use this to get a string you can use in multiple places in a template or so you can use the output as an argument for other template tags or filters.
</p><p><code>{% blocktrans %}</code> also supports <a href="#contextual-markers">contextual markers</a> using the <code>context</code> keyword:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans with name=user.username context "greeting" %}Hi {{ name }}{% endblocktrans %}</code></pre>
</div>
</div>
<p>Another feature <code>{% blocktrans %}</code> supports is the <code>trimmed</code> option. This option will remove newline characters from the beginning and the end of the content of the <code>{% blocktrans %}</code> tag, replace any whitespace at the beginning and end of a line and merge all lines into one using a space character to separate them. This is quite useful for indenting the content of a <code>{% blocktrans %}</code> tag without having the indentation characters end up in the corresponding entry in the PO file, which makes the translation process easier.
</p><p>For instance, the following <code>{% blocktrans %}</code> tag:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% blocktrans trimmed %}
  First sentence.
  Second paragraph.
{% endblocktrans %}</code></pre>
</div>
</div>
<p>will result in the entry "First sentence. Second paragraph." in the PO file, compared to "
  First sentence.
  Second sentence.
", if the <code>trimmed</code> option had not been specified.
</p><p><br />
</p>
</div>
<div id="string-literals-passed-to-tags-and-filters" class="section">
<h3><span class="mw-headline" id="String_literals_passed_to_tags_and_filters">String literals passed to tags and filters</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="21">String literals passed to tags and filters</mw:editsection></h3>
<p>You can translate string literals passed as arguments to tags and filters by using the familiar <code>_()</code> syntax:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% some_tag _("Page not found") value|yesno:_("yes,no") %}</code></pre>
</div>
</div>
<p>In this case, both the tag and the filter will see the translated string, so they don’t need to be aware of translations.
</p>
<div class="admonition note">
<p>Note
</p><p>In this example, the translation infrastructure will be passed the string <code>"yes,no"</code>, not the individual strings <code>"yes"</code> and <code>"no"</code>. The translated string will need to contain the comma so that the filter parsing code knows how to split up the arguments. For example, a German translator might translate the string <code>"yes,no"</code> as <code>"ja,nein"</code> (keeping the comma intact).
</p><p><br />
</p>
</div>
</div>
<div id="comments-for-translators-in-templates" class="section">
<p><span id="translator-comments-in-templates"></span>
</p>
<h3><span class="mw-headline" id="Comments_for_translators_in_templates">Comments for translators in templates</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="22">Comments for translators in templates</mw:editsection></h3>
<p>Just like with <a href="#translator-comments">Python code</a>, these notes for translators can be specified using comments, either with the <a href="/Django/docs/3.0.x/ref/templates/builtins#std-templatetag-comment" title="Django/docs/3.0.x/ref/templates/builtins">comment</a> tag:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% comment %}Translators: View verb{% endcomment %}
{% trans "View" %}

{% comment %}Translators: Short intro blurb{% endcomment %}
<p>{% blocktrans %}A multiline translatable
literal.{% endblocktrans %}p></code></pre>
</div>
</div>
<p>or with the <code>{#</code> … <code>#}</code> <a href="/Django/docs/3.0.x/ref/templates/language#template-comments" title="Django/docs/3.0.x/ref/templates/language">one-line comment constructs</a>:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{# Translators: Label of a button that triggers search #}
<button type="submit">{% trans "Go" %}button>

{# Translators: This is a text of the base template #}
{% blocktrans %}Ambiguous translatable block of text{% endblocktrans %}</code></pre>
</div>
</div>
<div class="admonition note">
<p>Note
</p><p>Just for completeness, these are the corresponding fragments of the resulting <code>.po</code> file:
</p>
<div class="highlight-po notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-po" dir="ltr"><code class="language-po">#. Translators: View verb
# path/to/template/file.html:10
msgid "View"
msgstr ""

#. Translators: Short intro blurb
# path/to/template/file.html:13
msgid ""
"A multiline translatable"
"literal."
msgstr ""

# ...

#. Translators: Label of a button that triggers search
# path/to/template/file.html:100
msgid "Go"
msgstr ""

#. Translators: This is a text of the base template
# path/to/template/file.html:103
msgid "Ambiguous translatable block of text"
msgstr ""</code></pre>
</div>
</div>
</div>
</div>
<div id="switching-language-in-templates" class="section">
<p><span id="std-templatetag-language"></span><span id="std:templatetag-language"></span>
</p>
<h3><span class="mw-headline" id="Switching_language_in_templates">Switching language in templates</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="23">Switching language in templates</mw:editsection></h3>
<p>If you want to select a language within a template, you can use the <code>language</code> template tag:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% load i18n %}

{% get_current_language as LANGUAGE_CODE %}

<p>{% trans "Welcome to our page" %}p>

{% language 'en' %}
    {% get_current_language as LANGUAGE_CODE %}
    
    <p>{% trans "Welcome to our page" %}p>
{% endlanguage %}</code></pre>
</div>
</div>
<p>While the first occurrence of “Welcome to our page” uses the current language, the second will always be in English.
</p><p><br />
</p>
</div>
<div id="other-tags" class="section">
<p><span id="i18n-template-tags"></span>
</p>
<h3><span class="mw-headline" id="Other_tags">Other tags</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="24">Other tags</mw:editsection></h3>
<p>These tags also require a <code>{% load i18n %}</code>.
</p>
<div id="get-available-languages" class="section">
<p><span id="std-templatetag-get_available_languages"></span><span id="std:templatetag-get_available_languages"></span>
</p>
<h4><span class="mw-headline" id="get_available_languages">get_available_languages</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="25">get available languages</mw:editsection></h4>
<p><code>{% get_available_languages as LANGUAGES %}</code> returns a list of tuples in which the first element is the <a href="/Django/docs/3.0.x/topics/i18n/index#term-language-code" title="Django/docs/3.0.x/topics/i18n/index">language code</a> and the second is the language name (translated into the currently active locale).
</p><p><br />
</p>
</div>
<div id="get-current-language" class="section">
<p><span id="std-templatetag-get_current_language"></span><span id="std:templatetag-get_current_language"></span>
</p>
<h4><span class="mw-headline" id="get_current_language">get_current_language</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="26">get current language</mw:editsection></h4>
<p><code>{% get_current_language as LANGUAGE_CODE %}</code> returns the current user’s preferred language as a string. Example: <code>en-us</code>. See <a href="#how-django-discovers-language-preference">How Django discovers language preference</a>.
</p><p><br />
</p>
</div>
<div id="get-current-language-bidi" class="section">
<p><span id="std-templatetag-get_current_language_bidi"></span><span id="std:templatetag-get_current_language_bidi"></span>
</p>
<h4><span class="mw-headline" id="get_current_language_bidi">get_current_language_bidi</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="27">get current language bidi</mw:editsection></h4>
<p><code>{% get_current_language_bidi as LANGUAGE_BIDI %}</code> returns the current locale’s direction. If <code>True</code>, it’s a right-to-left language, e.g. Hebrew, Arabic. If <code>False</code> it’s a left-to-right language, e.g. English, French, German, etc.
</p><p><br />
</p>
</div>
<div id="i18n-context-processor" class="section">
<p><span id="template-translation-vars"></span>
</p>
<h4><span class="mw-headline" id="i18n_context_processor">i18n context processor</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="28">i18n context processor</mw:editsection></h4>
<p>If you enable the <a href="/Django/docs/3.0.x/ref/templates/api#django.template.context_processors" title="Django/docs/3.0.x/ref/templates/api">django.template.context_processors.i18n</a> context processor, then each <code>RequestContext</code> will have access to <code>LANGUAGES</code>, <code>LANGUAGE_CODE</code>, and <code>LANGUAGE_BIDI</code> as defined above.
</p><p><br />
</p>
</div>
<div id="get-language-info" class="section">
<p><span id="std-templatetag-get_language_info"></span><span id="std:templatetag-get_language_info"></span>
</p>
<h4><span class="mw-headline" id="get_language_info">get_language_info</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="29">get language info</mw:editsection></h4>
<p>You can also retrieve information about any of the available languages using provided template tags and filters. To get information about a single language, use the <code>{% get_language_info %}</code> tag:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% get_language_info for LANGUAGE_CODE as lang %}
{% get_language_info for "pl" as lang %}</code></pre>
</div>
</div>
<p>You can then access the information:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">Language code: {{ lang.code }}<br>
Name of language: {{ lang.name_local }}<br>
Name in English: {{ lang.name }}<br>
Bi-directional: {{ lang.bidi }}
Name in the active language: {{ lang.name_translated }}</code></pre>
</div>
</div>
</div>
<div id="get-language-info-list" class="section">
<p><span id="std-templatetag-get_language_info_list"></span><span id="std:templatetag-get_language_info_list"></span>
</p>
<h4><span class="mw-headline" id="get_language_info_list">get_language_info_list</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="30">get language info list</mw:editsection></h4>
<p>You can also use the <code>{% get_language_info_list %}</code> template tag to retrieve information for a list of languages (e.g. active languages as specified in <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGES" title="Django/docs/3.0.x/ref/settings">LANGUAGES</a>). See <a href="#set-language-redirect-view">the section about the set_language redirect view</a> for an example of how to display a language selector using <code>{% get_language_info_list %}</code>.
</p><p>In addition to <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGES" title="Django/docs/3.0.x/ref/settings">LANGUAGES</a> style list of tuples, <code>{% get_language_info_list %}</code> supports lists of language codes. If you do this in your view:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">context = {'available_languages': ['en', 'es', 'fr']}
return render(request, 'mytemplate.html', context)</code></pre>
</div>
</div>
<p>you can iterate over those languages in the template:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% get_language_info_list for available_languages as langs %}
{% for lang in langs %} ... {% endfor %}</code></pre>
</div>
</div>
<p><span id="std-templatefilter-language_name" class="target"><span id="std:templatefilter-language_name"></span></span><span id="std-templatefilter-language_name_local" class="target"><span id="std:templatefilter-language_name_local"></span></span><span id="std-templatefilter-language_bidi" class="target"><span id="std:templatefilter-language_bidi"></span></span>
</p>
</div>
<div id="template-filters" class="section">
<p><span id="std-templatefilter-language_name_translated"></span><span id="std:templatefilter-language_name_translated"></span>
</p>
<h4><span class="mw-headline" id="Template_filters">Template filters</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="31">Template filters</mw:editsection></h4>
<p>There are also some filters available for convenience:
</p>
<ul><li><code><a href="/index.php?title=Template:LANGUAGE_CODE&action=edit&redlink=1" class="new" title="Template:LANGUAGE CODE (page does not exist)">Template:LANGUAGE CODE</a></code> (“German”)</li>
<li><code><a href="/index.php?title=Template:LANGUAGE_CODE&action=edit&redlink=1" class="new" title="Template:LANGUAGE CODE (page does not exist)">Template:LANGUAGE CODE</a></code> (“Deutsch”)</li>
<li><code><a href="/index.php?title=Template:LANGUAGE_CODE&action=edit&redlink=1" class="new" title="Template:LANGUAGE CODE (page does not exist)">Template:LANGUAGE CODE</a></code> (False)</li>
<li><code><a href="/index.php?title=Template:LANGUAGE_CODE&action=edit&redlink=1" class="new" title="Template:LANGUAGE CODE (page does not exist)">Template:LANGUAGE CODE</a></code> (“německy”, when active language is Czech)</li></ul>
<p><br />
</p>
</div>
</div>
</div>
<div id="internationalization-in-javascript-code" class="section">
<h2><span class="mw-headline" id="Internationalization:_in_JavaScript_code">Internationalization: in JavaScript code</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="32">Internationalization: in JavaScript code</mw:editsection></h2>
<p>Adding translations to JavaScript poses some problems:
</p>
<ul><li>JavaScript code doesn’t have access to a <code>gettext</code> implementation.</li>
<li>JavaScript code doesn’t have access to <code>.po</code> or <code>.mo</code> files; they need to be delivered by the server.</li>
<li>The translation catalogs for JavaScript should be kept as small as possible.</li></ul>
<p>Django provides an integrated solution for these problems: It passes the translations into JavaScript, so you can call <code>gettext</code>, etc., from within JavaScript.
</p><p>The main solution to these problems is the following <code>JavaScriptCatalog</code> view, which generates a JavaScript code library with functions that mimic the <code>gettext</code> interface, plus an array of translation strings.
</p>
<div id="module-django.views.i18n" class="section">
<p><span id="the-javascriptcatalog-view"></span>
</p>
<h3><span class="mw-headline" id="The_JavaScriptCatalog_view">The JavaScriptCatalog view</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="33">The JavaScriptCatalog view</mw:editsection></h3>
<dl>
<dt><i><span class="pre">class</span></i> <span class="sig-name descname"><span class="pre">JavaScriptCatalog</span></span><a href="/index.php?title=Django/docs/3.0.x/topics/_modules/django/views/i18n.html&action=edit&redlink=1" class="new" title="Django/docs/3.0.x/topics/ modules/django/views/i18n.html (page does not exist)"><span class="viewcode-link"><span class="pre">[source]</span></span></a></dt>
<dd><p>A view that produces a JavaScript code library with functions that mimic the <code>gettext</code> interface, plus an array of translation strings.</p>
<p><b>Attributes</b></p>
<dl>
<dt><span class="sig-name descname"><span class="pre">domain</span></span></dt>
<dd><p>Translation domain containing strings to add in the view output. Defaults to <code>'djangojs'</code>.</p></dd></dl>
<dl>
<dt><span class="sig-name descname"><span class="pre">packages</span></span></dt>
<dd><p>A list of <a href="/Django/docs/3.0.x/ref/applications#django.apps.AppConfig" title="Django/docs/3.0.x/ref/applications">application names</a> among installed applications. Those apps should contain a <code>locale</code> directory. All those catalogs plus all catalogs found in <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> (which are always included) are merged into one catalog. Defaults to <code>None</code>, which means that all available translations from all <a href="/Django/docs/3.0.x/ref/settings#std-setting-INSTALLED_APPS" title="Django/docs/3.0.x/ref/settings">INSTALLED_APPS</a> are provided in the JavaScript output.</p></dd></dl>
<p><b>Example with default values</b>:</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]</code></pre>
</div>
</div>
<p><b>Example with custom packages</b>:</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">urlpatterns = [
    path('jsi18n/myapp/',
         JavaScriptCatalog.as_view(packages=['your.app.label']),
         name='javascript-catalog'),
]</code></pre>
</div>
</div>
<p>If your root URLconf uses <a href="#django.conf.urls.i18n.i18n_patterns">i18n_patterns()</a>, <code>JavaScriptCatalog</code> must also be wrapped by <code>i18n_patterns()</code> for the catalog to be correctly generated.</p>
<p><b>Example with</b> <code>i18n_patterns()</code>:</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.conf.urls.i18n import i18n_patterns

urlpatterns = i18n_patterns(
    path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
)</code></pre>
</div>
</div></dd></dl>
<p>The precedence of translations is such that the packages appearing later in the <code>packages</code> argument have higher precedence than the ones appearing at the beginning. This is important in the case of clashing translations for the same literal.
</p><p>If you use more than one <code>JavaScriptCatalog</code> view on a site and some of them define the same strings, the strings in the catalog that was loaded last take precedence.
</p><p><br />
</p>
</div>
<div id="using-the-javascript-translation-catalog" class="section">
<h3><span class="mw-headline" id="Using_the_JavaScript_translation_catalog">Using the JavaScript translation catalog</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="34">Using the JavaScript translation catalog</mw:editsection></h3>
<p>To use the catalog, pull in the dynamically generated script like this:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django"><script type="text/javascript" src="{% url 'javascript-catalog' %}">script></code></pre>
</div>
</div>
<p>This uses reverse URL lookup to find the URL of the JavaScript catalog view. When the catalog is loaded, your JavaScript code can use the following methods:
</p>
<ul><li><code> gettext</code></li>
<li><code> ngettext</code></li>
<li><code> interpolate</code></li>
<li><code> get_format</code></li>
<li><code> gettext_noop</code></li>
<li><code> pgettext</code></li>
<li><code> npgettext</code></li>
<li><code> pluralidx</code></li></ul>
<div id="gettext" class="section">
<h4><span class="mw-headline" id="gettext">gettext</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="35">gettext</mw:editsection></h4>
<p>The <code>gettext</code> function behaves similarly to the standard <code>gettext</code> interface within your Python code:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">document.write(gettext('this is to be translated'));</code></pre>
</div>
</div>
</div>
<div id="ngettext" class="section">
<h4><span class="mw-headline" id="ngettext">ngettext</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="36">ngettext</mw:editsection></h4>
<p>The <code>ngettext</code> function provides an interface to pluralize words and phrases:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">const objectCount = 1 // or 0, or 2, or 3, ...
const string = ngettext(
    'literal for the singular case',
    'literal for the plural case',
    objectCount
);</code></pre>
</div>
</div>
</div>
<div id="interpolate" class="section">
<h4><span class="mw-headline" id="interpolate">interpolate</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="37">interpolate</mw:editsection></h4>
<p>The <code>interpolate</code> function supports dynamically populating a format string. The interpolation syntax is borrowed from Python, so the <code>interpolate</code> function supports both positional and named interpolation:
</p>
<ul>
<li><p>Positional interpolation: <code>obj</code> contains a JavaScript Array object whose elements values are then sequentially interpolated in their corresponding <code>fmt</code> placeholders in the same order they appear. For example:</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">const formats = ngettext(
  'There is %s object. Remaining: %s',
  'There are %s objects. Remaining: %s',
  11
);
const string = interpolate(formats, [11, 20]);
// string is 'There are 11 objects. Remaining: 20'</code></pre>
</div>
</div></li>
<li><p>Named interpolation: This mode is selected by passing the optional boolean <code>named</code> parameter as <code>true</code>. <code>obj</code> contains a JavaScript object or associative array. For example:</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">const data = {
  count: 10,
  total: 50
};

const formats = ngettext(
    'Total: %(total)s, there is %(count)s object',
    'there are %(count)s of a total of %(total)s objects',
    data.count
);
const string = interpolate(formats, data, true);</code></pre>
</div>
</div></li></ul>
<p>You shouldn’t go over the top with string interpolation, though: this is still JavaScript, so the code has to make repeated regular-expression substitutions. This isn’t as fast as string interpolation in Python, so keep it to those cases where you really need it (for example, in conjunction with <code>ngettext</code> to produce proper pluralizations).
</p><p><br />
</p>
</div>
<div id="get-format" class="section">
<h4><span class="mw-headline" id="get_format">get_format</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="38">get format</mw:editsection></h4>
<p>The <code>get_format</code> function has access to the configured i18n formatting settings and can retrieve the format string for a given setting name:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">document.write(get_format('DATE_FORMAT'));
// 'N j, Y'</code></pre>
</div>
</div>
<p>It has access to the following settings:
</p>
<ul><li><a href="/Django/docs/3.0.x/ref/settings#std-setting-DATE_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> DATE_FORMAT</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-DATE_INPUT_FORMATS" title="Django/docs/3.0.x/ref/settings"><code> DATE_INPUT_FORMATS</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-DATETIME_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> DATETIME_FORMAT</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-DATETIME_INPUT_FORMATS" title="Django/docs/3.0.x/ref/settings"><code> DATETIME_INPUT_FORMATS</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-DECIMAL_SEPARATOR" title="Django/docs/3.0.x/ref/settings"><code> DECIMAL_SEPARATOR</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-FIRST_DAY_OF_WEEK" title="Django/docs/3.0.x/ref/settings"><code> FIRST_DAY_OF_WEEK</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-MONTH_DAY_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> MONTH_DAY_FORMAT</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-NUMBER_GROUPING" title="Django/docs/3.0.x/ref/settings"><code> NUMBER_GROUPING</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-SHORT_DATE_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> SHORT_DATE_FORMAT</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-SHORT_DATETIME_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> SHORT_DATETIME_FORMAT</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-THOUSAND_SEPARATOR" title="Django/docs/3.0.x/ref/settings"><code> THOUSAND_SEPARATOR</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-TIME_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> TIME_FORMAT</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-TIME_INPUT_FORMATS" title="Django/docs/3.0.x/ref/settings"><code> TIME_INPUT_FORMATS</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-YEAR_MONTH_FORMAT" title="Django/docs/3.0.x/ref/settings"><code> YEAR_MONTH_FORMAT</code></a></li></ul>
<p>This is useful for maintaining formatting consistency with the Python-rendered values.
</p><p><br />
</p>
</div>
<div id="gettext-noop" class="section">
<h4><span class="mw-headline" id="gettext_noop">gettext_noop</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="39">gettext noop</mw:editsection></h4>
<p>This emulates the <code>gettext</code> function but does nothing, returning whatever is passed to it:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">document.write(gettext_noop('this will not be translated'));</code></pre>
</div>
</div>
<p>This is useful for stubbing out portions of the code that will need translation in the future.
</p><p><br />
</p>
</div>
<div id="pgettext" class="section">
<h4><span class="mw-headline" id="pgettext">pgettext</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="40">pgettext</mw:editsection></h4>
<p>The <code>pgettext</code> function behaves like the Python variant (<a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">pgettext()</a>), providing a contextually translated word:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">document.write(pgettext('month name', 'May'));</code></pre>
</div>
</div>
</div>
<div id="npgettext" class="section">
<h4><span class="mw-headline" id="npgettext">npgettext</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="41">npgettext</mw:editsection></h4>
<p>The <code>npgettext</code> function also behaves like the Python variant (<a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">npgettext()</a>), providing a <b>pluralized</b> contextually translated word:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">document.write(npgettext('group', 'party', 1));
// party
document.write(npgettext('group', 'party', 2));
// parties</code></pre>
</div>
</div>
</div>
<div id="pluralidx" class="section">
<h4><span class="mw-headline" id="pluralidx">pluralidx</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="42">pluralidx</mw:editsection></h4>
<p>The <code>pluralidx</code> function works in a similar way to the <a href="/Django/docs/3.0.x/ref/templates/builtins#std-templatefilter-pluralize" title="Django/docs/3.0.x/ref/templates/builtins">pluralize</a> template filter, determining if a given <code>count</code> should use a plural form of a word or not:
</p>
<div class="highlight-javascript notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-javascript" dir="ltr"><code class="language-javascript">document.write(pluralidx(0));
// true
document.write(pluralidx(1));
// false
document.write(pluralidx(2));
// true</code></pre>
</div>
</div>
<p>In the simplest case, if no custom pluralization is needed, this returns <code>false</code> for the integer <code>1</code> and <code>true</code> for all other numbers.
</p><p>However, pluralization is not this simple in all languages. If the language does not support pluralization, an empty value is provided.
</p><p>Additionally, if there are complex rules around pluralization, the catalog view will render a conditional expression. This will evaluate to either a <code>true</code> (should pluralize) or <code>false</code> (should <b>not</b> pluralize) value.
</p><p><br />
</p>
</div>
</div>
<div id="the-jsoncatalog-view" class="section">
<h3><span class="mw-headline" id="The_JSONCatalog_view">The JSONCatalog view</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="43">The JSONCatalog view</mw:editsection></h3>
<dl>
<dt><i><span class="pre">class</span></i> <span class="sig-name descname"><span class="pre">JSONCatalog</span></span><a href="/index.php?title=Django/docs/3.0.x/topics/_modules/django/views/i18n.html&action=edit&redlink=1" class="new" title="Django/docs/3.0.x/topics/ modules/django/views/i18n.html (page does not exist)"><span class="viewcode-link"><span class="pre">[source]</span></span></a></dt>
<dd><p>In order to use another client-side library to handle translations, you may want to take advantage of the <code>JSONCatalog</code> view. It’s similar to <a href="#django.views.i18n.JavaScriptCatalog">JavaScriptCatalog</a> but returns a JSON response.</p>
<p>See the documentation for <a href="#django.views.i18n.JavaScriptCatalog">JavaScriptCatalog</a> to learn about possible values and use of the <code>domain</code> and <code>packages</code> attributes.</p>
<p>The response format is as follows:</p>
<div class="highlight-text notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-text" dir="ltr"><code class="language-text">{
    "catalog": {
        # Translations catalog
    },
    "formats": {
        # Language formats for date, time, etc.
    },
    "plural": "..."  # Expression for plural forms, or null.
}</code></pre>
</div>
</div></dd></dl>
<p><br />
</p>
</div>
<div id="note-on-performance" class="section">
<h3><span class="mw-headline" id="Note_on_performance">Note on performance</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="44">Note on performance</mw:editsection></h3>
<p>The various JavaScript/JSON i18n views generate the catalog from <code>.mo</code> files on every request. Since its output is constant, at least for a given version of a site, it’s a good candidate for caching.
</p><p>Server-side caching will reduce CPU load. It’s easily implemented with the <a href="/Django/docs/3.0.x/topics/cache#django.views.decorators.cache" title="Django/docs/3.0.x/topics/cache">cache_page()</a> decorator. To trigger cache invalidation when your translations change, provide a version-dependent key prefix, as shown in the example below, or map the view at a version-dependent URL:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.views.decorators.cache import cache_page
from django.views.i18n import JavaScriptCatalog

# The value returned by get_version() must change when translations change.
urlpatterns = [
    path('jsi18n/',
         cache_page(86400, key_prefix='js18n-%s' % get_version())(JavaScriptCatalog.as_view()),
         name='javascript-catalog'),
]</code></pre>
</div>
</div>
<p>Client-side caching will save bandwidth and make your site load faster. If you’re using ETags (<a href="/Django/docs/3.0.x/ref/middleware#django.middleware.http" title="Django/docs/3.0.x/ref/middleware">ConditionalGetMiddleware</a>), you’re already covered. Otherwise, you can apply <a href="/Django/docs/3.0.x/topics/conditional-view-processing#conditional-decorators" title="Django/docs/3.0.x/topics/conditional-view-processing">conditional decorators</a>. In the following example, the cache is invalidated whenever you restart your application server:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.utils import timezone
from django.views.decorators.http import last_modified
from django.views.i18n import JavaScriptCatalog

last_modified_date = timezone.now()

urlpatterns = [
    path('jsi18n/',
         last_modified(lambda req, **kw: last_modified_date)(JavaScriptCatalog.as_view()),
         name='javascript-catalog'),
]</code></pre>
</div>
</div>
<p>You can even pre-generate the JavaScript catalog as part of your deployment procedure and serve it as a static file. This radical technique is implemented in <a rel="nofollow" class="external text" href="https://django-statici18n.readthedocs.io/en/latest/">django-statici18n</a>.
</p><p><br />
</p>
</div>
</div>
<div id="module-django.conf.urls.i18n" class="section">
<p><span id="internationalization-in-url-patterns"></span><span id="url-internationalization"></span>
</p>
<h2><span class="mw-headline" id="Internationalization:_in_URL_patterns">Internationalization: in URL patterns</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="45">Internationalization: in URL patterns</mw:editsection></h2>
<p>Django provides two mechanisms to internationalize URL patterns:
</p>
<ul><li>Adding the language prefix to the root of the URL patterns to make it possible for <a href="/Django/docs/3.0.x/ref/middleware#django.middleware.locale" title="Django/docs/3.0.x/ref/middleware">LocaleMiddleware</a> to detect the language to activate from the requested URL.</li>
<li>Making URL patterns themselves translatable via the <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.gettext_lazy()</a> function.</li></ul>
<div class="admonition warning">
<p>Warning
</p><p>Using either one of these features requires that an active language be set for each request; in other words, you need to have <a href="/Django/docs/3.0.x/ref/middleware#django.middleware.locale" title="Django/docs/3.0.x/ref/middleware">django.middleware.locale.LocaleMiddleware</a> in your <a href="/Django/docs/3.0.x/ref/settings#std-setting-MIDDLEWARE" title="Django/docs/3.0.x/ref/settings">MIDDLEWARE</a> setting.
</p><p><br />
</p>
</div>
<div id="language-prefix-in-url-patterns" class="section">
<h3><span class="mw-headline" id="Language_prefix_in_URL_patterns">Language prefix in URL patterns</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="46">Language prefix in URL patterns</mw:editsection></h3>
<dl><dt><span class="sig-name descname">i18n_patterns</span><span class="sig-paren">(</span><i>*urls</i>, <i>prefix_default_language=True</i><span class="sig-paren">)</span><a href="/Django/docs/3.0.x/_modules/django/conf/urls/i18n#i18n_patterns" title="Django/docs/3.0.x/ modules/django/conf/urls/i18n">[source]</a></dt>
<dd></dd></dl>
<p>This function can be used in a root URLconf and Django will automatically prepend the current active language code to all URL patterns defined within <a href="#django.conf.urls.i18n.i18n_patterns">i18n_patterns()</a>.
</p><p>Setting <code>prefix_default_language</code> to <code>False</code> removes the prefix from the default language (<a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a>). This can be useful when adding translations to existing site so that the current URLs won’t change.
</p><p>Example URL patterns:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path

from about import views as about_views
from news import views as news_views
from sitemap.views import sitemap

urlpatterns = [
    path('sitemap.xml', sitemap, name='sitemap-xml'),
]

news_patterns = ([
    path('', news_views.index, name='index'),
    path('category//', news_views.category, name='category'),
    path('/', news_views.details, name='detail'),
], 'news')

urlpatterns += i18n_patterns(
    path('about/', about_views.main, name='about'),
    path('news/', include(news_patterns, namespace='news')),
)</code></pre>
</div>
</div>
<p>After defining these URL patterns, Django will automatically add the language prefix to the URL patterns that were added by the <code>i18n_patterns</code> function. Example:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">>>> from django.urls import reverse
>>> from django.utils.translation import activate

>>> activate('en')
>>> reverse('sitemap-xml')
'/sitemap.xml'
>>> reverse('news:index')
'/en/news/'

>>> activate('nl')
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
'/nl/news/news-slug/'</code></pre>
</div>
</div>
<p>With <code>prefix_default_language=False</code> and <code>LANGUAGE_CODE='en'</code>, the URLs will be:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">>>> activate('en')
>>> reverse('news:index')
'/news/'

>>> activate('nl')
>>> reverse('news:index')
'/nl/news/'</code></pre>
</div>
</div>
<div class="admonition warning">
<p>Warning
</p><p><a href="#django.conf.urls.i18n.i18n_patterns">i18n_patterns()</a> is only allowed in a root URLconf. Using it within an included URLconf will throw an <a href="/Django/docs/3.0.x/ref/exceptions#django.core.exceptions" title="Django/docs/3.0.x/ref/exceptions">ImproperlyConfigured</a> exception.
</p><p><br />
</p>
</div>
<div class="admonition warning">
<p>Warning
</p><p>Ensure that you don’t have non-prefixed URL patterns that might collide with an automatically-added language prefix.
</p><p><br />
</p>
</div>
</div>
<div id="translating-url-patterns" class="section">
<p><span id="translating-urlpatterns"></span>
</p>
<h3><span class="mw-headline" id="Translating_URL_patterns">Translating URL patterns</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="47">Translating URL patterns</mw:editsection></h3>
<p>URL patterns can also be marked translatable using the <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">gettext_lazy()</a> function. Example:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path
from django.utils.translation import gettext_lazy as _

from about import views as about_views
from news import views as news_views
from sitemaps.views import sitemap

urlpatterns = [
    path('sitemap.xml', sitemap, name='sitemap-xml'),
]

news_patterns = ([
    path('', news_views.index, name='index'),
    path(_('category//'), news_views.category, name='category'),
    path('/', news_views.details, name='detail'),
], 'news')

urlpatterns += i18n_patterns(
    path(_('about/'), about_views.main, name='about'),
    path(_('news/'), include(news_patterns, namespace='news')),
)</code></pre>
</div>
</div>
<p>After you’ve created the translations, the <a href="/Django/docs/3.0.x/ref/urlresolvers#django.urls" title="Django/docs/3.0.x/ref/urlresolvers">reverse()</a> function will return the URL in the active language. Example:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">>>> from django.urls import reverse
>>> from django.utils.translation import activate

>>> activate('en')
>>> reverse('news:category', kwargs={'slug': 'recent'})
'/en/news/category/recent/'

>>> activate('nl')
>>> reverse('news:category', kwargs={'slug': 'recent'})
'/nl/nieuws/categorie/recent/'</code></pre>
</div>
</div>
<div class="admonition warning">
<p>Warning
</p><p>In most cases, it’s best to use translated URLs only within a language code prefixed block of patterns (using <a href="#django.conf.urls.i18n.i18n_patterns">i18n_patterns()</a>), to avoid the possibility that a carelessly translated URL causes a collision with a non-translated URL pattern.
</p><p><br />
</p>
</div>
</div>
<div id="reversing-in-templates" class="section">
<p><span id="id2"></span>
</p>
<h3><span class="mw-headline" id="Reversing_in_templates">Reversing in templates</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="48">Reversing in templates</mw:editsection></h3>
<p>If localized URLs get reversed in templates they always use the current language. To link to a URL in another language use the <a href="#std-templatetag-language">language</a> template tag. It enables the given language in the enclosed template section:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% load i18n %}

{% get_available_languages as languages %}

{% trans "View this category in:" %}
{% for lang_code, lang_name in languages %}
    {% language lang_code %}
    <a href="{% url 'category' slug=category.slug %}">{{ lang_name }}a>
    {% endlanguage %}
{% endfor %}</code></pre>
</div>
</div>
<p>The <a href="#std-templatetag-language">language</a> tag expects the language code as the only argument.
</p><p><br />
</p>
</div>
</div>
<div id="localization-how-to-create-language-files" class="section">
<p><span id="how-to-create-language-files"></span>
</p>
<h2><span class="mw-headline" id="Localization:_how_to_create_language_files">Localization: how to create language files</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="49">Localization: how to create language files</mw:editsection></h2>
<p>Once the string literals of an application have been tagged for later translation, the translation themselves need to be written (or obtained). Here’s how that works.
</p>
<div id="message-files" class="section">
<h3><span class="mw-headline" id="Message_files">Message files</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="50">Message files</mw:editsection></h3>
<p>The first step is to create a <a href="/Django/docs/3.0.x/topics/i18n/index#term-message-file" title="Django/docs/3.0.x/topics/i18n/index">message file</a> for a new language. A message file is a plain-text file, representing a single language, that contains all available translation strings and how they should be represented in the given language. Message files have a <code>.po</code> file extension.
</p><p>Django comes with a tool, <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin makemessages</a>, that automates the creation and upkeep of these files.
</p>
<div class="admonition-gettext-utilities admonition">
<p>Gettext utilities
</p><p>The <code>makemessages</code> command (and <code>compilemessages</code> discussed later) use commands from the GNU gettext toolset: <code>xgettext</code>, <code>msgfmt</code>, <code>msgmerge</code> and <code>msguniq</code>.
</p><p>The minimum version of the <code>gettext</code> utilities supported is 0.15.
</p><p><br />
</p>
</div>
<p>To create or update a message file, run this command:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">django-admin makemessages -l de</code></pre>
</div>
</div>
<p>…where <code>de</code> is the <a href="/Django/docs/3.0.x/topics/i18n/index#term-locale-name" title="Django/docs/3.0.x/topics/i18n/index">locale name</a> for the message file you want to create. For example, <code>pt_BR</code> for Brazilian Portuguese, <code>de_AT</code> for Austrian German or <code>id</code> for Indonesian.
</p><p>The script should be run from one of two places:
</p>
<ul><li>The root directory of your Django project (the one that contains <code>manage.py</code>).</li>
<li>The root directory of one of your Django apps.</li></ul>
<p>The script runs over your project source tree or your application source tree and pulls out all strings marked for translation (see <a href="#how-django-discovers-translations">How Django discovers translations</a> and be sure <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> is configured correctly). It creates (or updates) a message file in the directory <code>locale/LANG/LC_MESSAGES</code>. In the <code>de</code> example, the file will be <code>locale/de/LC_MESSAGES/django.po</code>.
</p><p>When you run <code>makemessages</code> from the root directory of your project, the extracted strings will be automatically distributed to the proper message files. That is, a string extracted from a file of an app containing a <code>locale</code> directory will go in a message file under that directory. A string extracted from a file of an app without any <code>locale</code> directory will either go in a message file under the directory listed first in <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> or will generate an error if <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> is empty.
</p><p>By default <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin makemessages</a> examines every file that has the <code>.html</code>, <code>.txt</code> or <code>.py</code> file extension. If you want to override that default, use the <a href="/Django/docs/3.0.x/ref/django-admin#cmdoption-makemessages-extension" title="Django/docs/3.0.x/ref/django-admin">--extension</a> or <code>-e</code> option to specify the file extensions to examine:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">django-admin makemessages -l de -e txt</code></pre>
</div>
</div>
<p>Separate multiple extensions with commas and/or use <code>-e</code> or <code>--extension</code> multiple times:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">django-admin makemessages -l de -e html,txt -e xml</code></pre>
</div>
</div>
<div class="admonition warning">
<p>Warning
</p><p>When <a href="#creating-message-files-from-js-code">creating message files from JavaScript source code</a> you need to use the special <code>djangojs</code> domain, <b>not</b> <code>-e js</code>.
</p><p><br />
</p>
</div>
<div class="admonition-using-jinja2-templates admonition">
<p>Using Jinja2 templates?
</p><p><a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a> doesn’t understand the syntax of Jinja2 templates. To extract strings from a project containing Jinja2 templates, use <a rel="nofollow" class="external text" href="http://babel.pocoo.org/en/latest/messages.html#message-extraction">Message Extracting</a> from <a rel="nofollow" class="external text" href="http://babel.pocoo.org/">Babel</a> instead.
</p><p>Here’s an example <code>babel.cfg</code> configuration file:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python"># Extraction from Python source files
[python: **.py]

# Extraction from Jinja2 templates
[jinja2: **.jinja]
extensions = jinja2.ext.with_</code></pre>
</div>
</div>
<p>Make sure you list all extensions you’re using! Otherwise Babel won’t recognize the tags defined by these extensions and will ignore Jinja2 templates containing them entirely.
</p><p>Babel provides similar features to <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a>, can replace it in general, and doesn’t depend on <code>gettext</code>. For more information, read its documentation about <a rel="nofollow" class="external text" href="http://babel.pocoo.org/en/latest/messages.html">working with message catalogs</a>.
</p><p><br />
</p>
</div>
<div class="admonition-no-gettext admonition">
<p>No gettext?
</p><p>If you don’t have the <code>gettext</code> utilities installed, <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a> will create empty files. If that’s the case, either install the <code>gettext</code> utilities or copy the English message file (<code>locale/en/LC_MESSAGES/django.po</code>) if available and use it as a starting point, which is an empty translation file.
</p><p><br />
</p>
</div>
<div class="admonition-working-on-windows admonition">
<p>Working on Windows?
</p><p>If you’re using Windows and need to install the GNU gettext utilities so <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a> works, see <a href="#gettext-on-windows">gettext on Windows</a> for more information.
</p><p><br />
</p>
</div>
<p>Each <code>.po</code> file contains a small bit of metadata, such as the translation maintainer’s contact information, but the bulk of the file is a list of <b>messages</b> – mappings between translation strings and the actual translated text for the particular language.
</p><p>For example, if your Django app contained a translation string for the text <code>"Welcome to my site."</code>, like so:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">_("Welcome to my site.")</code></pre>
</div>
</div>
<p>…then <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin makemessages</a> will have created a <code>.po</code> file containing the following snippet – a message:
</p>
<div class="highlight-po notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-po" dir="ltr"><code class="language-po">#: path/to/python/module.py:23
msgid "Welcome to my site."
msgstr ""</code></pre>
</div>
</div>
<p>A quick explanation:
</p>
<ul><li><code>msgid</code> is the translation string, which appears in the source. Don’t change it.</li>
<li><code>msgstr</code> is where you put the language-specific translation. It starts out empty, so it’s your responsibility to change it. Make sure you keep the quotes around your translation.</li>
<li>As a convenience, each message includes, in the form of a comment line prefixed with <code>#</code> and located above the <code>msgid</code> line, the filename and line number from which the translation string was gleaned.</li></ul>
<p>Long messages are a special case. There, the first string directly after the <code>msgstr</code> (or <code>msgid</code>) is an empty string. Then the content itself will be written over the next few lines as one string per line. Those strings are directly concatenated. Don’t forget trailing spaces within the strings; otherwise, they’ll be tacked together without whitespace!
</p>
<div class="admonition-mind-your-charset admonition">
<p>Mind your charset
</p><p>Due to the way the <code>gettext</code> tools work internally and because we want to allow non-ASCII source strings in Django’s core and your applications, you <b>must</b> use UTF-8 as the encoding for your PO files (the default when PO files are created). This means that everybody will be using the same encoding, which is important when Django processes the PO files.
</p><p><br />
</p>
</div>
<div class="admonition-fuzzy-entries admonition">
<p>Fuzzy entries
</p><p><a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a> sometimes generates translation entries marked as fuzzy, e.g. when translations are inferred from previously translated strings. By default, fuzzy entries are <b>not</b> processed by <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">compilemessages</a>.
</p><p><br />
</p>
</div>
<p>To reexamine all source code and templates for new translation strings and update all message files for <b>all</b> languages, run this:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">django-admin makemessages -a</code></pre>
</div>
</div>
</div>
<div id="compiling-message-files" class="section">
<h3><span class="mw-headline" id="Compiling_message_files">Compiling message files</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="51">Compiling message files</mw:editsection></h3>
<p>After you create your message file – and each time you make changes to it – you’ll need to compile it into a more efficient form, for use by <code>gettext</code>. Do this with the <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin compilemessages</a> utility.
</p><p>This tool runs over all available <code>.po</code> files and creates <code>.mo</code> files, which are binary files optimized for use by <code>gettext</code>. In the same directory from which you ran <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin makemessages</a>, run <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin compilemessages</a> like this:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">django-admin compilemessages</code></pre>
</div>
</div>
<p>That’s it. Your translations are ready for use.
</p>
<div class="admonition-working-on-windows admonition">
<p>Working on Windows?
</p><p>If you’re using Windows and need to install the GNU gettext utilities so <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin compilemessages</a> works see <a href="#gettext-on-windows">gettext on Windows</a> for more information.
</p><p><br />
</p>
</div>
<div class="admonition-po-files-encoding-and-bom-usage admonition">
<p>.po files: Encoding and BOM usage.
</p><p>Django only supports <code>.po</code> files encoded in UTF-8 and without any BOM (Byte Order Mark) so if your text editor adds such marks to the beginning of files by default then you will need to reconfigure it.
</p><p><br />
</p>
</div>
</div>
<div id="troubleshooting-gettext-incorrectly-detects-python-format-in-strings-with-percent-signs" class="section">
<h3><span id="Troubleshooting:_gettext()_incorrectly_detects_python-format_in_strings_with_percent_signs"></span><span class="mw-headline" id="Troubleshooting:_gettext.28.29_incorrectly_detects_python-format_in_strings_with_percent_signs">Troubleshooting: gettext() incorrectly detects python-format in strings with percent signs</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="52">Troubleshooting: gettext() incorrectly detects python-format in strings with percent signs</mw:editsection></h3>
<p>In some cases, such as strings with a percent sign followed by a space and a <a rel="nofollow" class="external text" href="https://docs.python.org/3/library/stdtypes.html#old-string-formatting">string conversion type</a> (e.g. <code>_("10% interest")</code>), <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">gettext()</a> incorrectly flags strings with <code>python-format</code>.
</p><p>If you try to compile message files with incorrectly flagged strings, you’ll get an error message like <code>number of format specifications in 'msgid' and 'msgstr' does not match</code> or <code>'msgstr' is not a valid Python format string, unlike 'msgid'</code>.
</p><p>To workaround this, you can escape percent signs by adding a second percent sign:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.utils.translation import gettext as _
output = _("10%% interest")</code></pre>
</div>
</div>
<p>Or you can use <code>no-python-format</code> so that all percent signs are treated as literals:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python"># xgettext:no-python-format
output = _("10% interest")</code></pre>
</div>
</div>
</div>
<div id="creating-message-files-from-javascript-source-code" class="section">
<p><span id="creating-message-files-from-js-code"></span>
</p>
<h3><span class="mw-headline" id="Creating_message_files_from_JavaScript_source_code">Creating message files from JavaScript source code</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="53">Creating message files from JavaScript source code</mw:editsection></h3>
<p>You create and update the message files the same way as the other Django message files – with the <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin makemessages</a> tool. The only difference is you need to explicitly specify what in gettext parlance is known as a domain in this case the <code>djangojs</code> domain, by providing a <code>-d djangojs</code> parameter, like this:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">django-admin makemessages -d djangojs -l de</code></pre>
</div>
</div>
<p>This would create or update the message file for JavaScript for German. After updating message files, run <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin compilemessages</a> the same way as you do with normal Django message files.
</p><p><br />
</p>
</div>
<div id="gettext-on-windows" class="section">
<p><span id="id3"></span>
</p>
<h3><span class="mw-headline" id="gettext_on_Windows">gettext on Windows</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="54">gettext on Windows</mw:editsection></h3>
<p>This is only needed for people who either want to extract message IDs or compile message files (<code>.po</code>). Translation work itself involves editing existing files of this type, but if you want to create your own message files, or want to test or compile a changed message file, download <a rel="nofollow" class="external text" href="https://mlocati.github.io/articles/gettext-iconv-windows.html">a precompiled binary installer</a>.
</p><p>You may also use <code>gettext</code> binaries you have obtained elsewhere, so long as the <code>xgettext --version</code> command works properly. Do not attempt to use Django translation utilities with a <code>gettext</code> package if the command <code>xgettext --version</code> entered at a Windows command prompt causes a popup window saying “xgettext.exe has generated errors and will be closed by Windows”.
</p><p><br />
</p>
</div>
<div id="customizing-the-makemessages-command" class="section">
<p><span id="customizing-makemessages"></span>
</p>
<h3><span class="mw-headline" id="Customizing_the_makemessages_command">Customizing the makemessages command</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="55">Customizing the makemessages command</mw:editsection></h3>
<p>If you want to pass additional parameters to <code>xgettext</code>, you need to create a custom <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a> command and override its <code>xgettext_options</code> attribute:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.core.management.commands import makemessages

class Command(makemessages.Command):
    xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']</code></pre>
</div>
</div>
<p>If you need more flexibility, you could also add a new argument to your custom <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">makemessages</a> command:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.core.management.commands import makemessages

class Command(makemessages.Command):

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            '--extra-keyword',
            dest='xgettext_keywords',
            action='append',
        )

    def handle(self, *args, **options):
        xgettext_keywords = options.pop('xgettext_keywords')
        if xgettext_keywords:
            self.xgettext_options = (
                makemessages.Command.xgettext_options[:] +
                ['--keyword=%s' % kwd for kwd in xgettext_keywords]
            )
        super().handle(*args, **options)</code></pre>
</div>
</div>
</div>
</div>
<div id="miscellaneous" class="section">
<h2><span class="mw-headline" id="Miscellaneous">Miscellaneous</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="56">Miscellaneous</mw:editsection></h2>
<div id="the-set-language-redirect-view" class="section">
<p><span id="set-language-redirect-view"></span>
</p>
<h3><span class="mw-headline" id="The_set_language_redirect_view">The set_language redirect view</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="57">The set language redirect view</mw:editsection></h3>
<dl><dt><span class="sig-name descname"><span class="pre">set_language</span></span><span class="sig-paren">(</span><i><span class="n"><span class="pre">request</span></span></i><span class="sig-paren">)</span><a href="/index.php?title=Django/docs/3.0.x/topics/_modules/django/views/i18n.html&action=edit&redlink=1" class="new" title="Django/docs/3.0.x/topics/ modules/django/views/i18n.html (page does not exist)"><span class="viewcode-link"><span class="pre">[source]</span></span></a></dt>
<dd></dd></dl>
<p>As a convenience, Django comes with a view, <a href="#django.views.i18n.set_language">django.views.i18n.set_language()</a>, that sets a user’s language preference and redirects to a given URL or, by default, back to the previous page.
</p><p>Activate this view by adding the following line to your URLconf:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">path('i18n/', include('django.conf.urls.i18n')),</code></pre>
</div>
</div>
<p>(Note that this example makes the view available at <code>/i18n/setlang/</code>.)
</p>
<div class="admonition warning">
<p>Warning
</p><p>Make sure that you don’t include the above URL within <a href="#django.conf.urls.i18n.i18n_patterns">i18n_patterns()</a> - it needs to be language-independent itself to work correctly.
</p><p><br />
</p>
</div>
<p>The view expects to be called via the <code>POST</code> method, with a <code>language</code> parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. It also saves the language choice in a cookie that is named <code>django_language</code> by default. (The name can be changed through the <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_NAME" title="Django/docs/3.0.x/ref/settings">LANGUAGE_COOKIE_NAME</a> setting.)
</p><p>After setting the language choice, Django looks for a <code>next</code> parameter in the <code>POST</code> or <code>GET</code> data. If that is found and Django considers it to be a safe URL (i.e. it doesn’t point to a different host and uses a safe scheme), a redirect to that URL will be performed. Otherwise, Django may fall back to redirecting the user to the URL from the <code>Referer</code> header or, if it is not set, to <code>/</code>, depending on the nature of the request:
</p>
<ul><li>For AJAX requests, the fallback will be performed only if the <code>next</code> parameter was set. Otherwise a 204 status code (No Content) will be returned.</li>
<li>For non-AJAX requests, the fallback will always be performed.</li></ul>
<p>Here’s example HTML template code:
</p>
<div class="highlight-html+django notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-html+django" dir="ltr"><code class="language-html+django">{% load i18n %}

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}">
    <select name="language">
        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            option>
        {% endfor %}
    select>
    <input type="submit" value="Go">
form></code></pre>
</div>
</div>
<p>In this example, Django looks up the URL of the page to which the user will be redirected in the <code>redirect_to</code> context variable.
</p><p><br />
</p>
</div>
<div id="explicitly-setting-the-active-language" class="section">
<p><span id="id4"></span>
</p>
<h3><span class="mw-headline" id="Explicitly_setting_the_active_language">Explicitly setting the active language</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="58">Explicitly setting the active language</mw:editsection></h3>
<p>You may want to set the active language for the current session explicitly. Perhaps a user’s language preference is retrieved from another system, for example. You’ve already been introduced to <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.activate()</a>. That applies to the current thread only. To persist the language for the entire session in a cookie, set the <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_NAME" title="Django/docs/3.0.x/ref/settings">LANGUAGE_COOKIE_NAME</a> cookie on the response:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.conf import settings
from django.http import HttpResponse
from django.utils import translation
user_language = 'fr'
translation.activate(user_language)
response = HttpResponse(...)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)</code></pre>
</div>
</div>
<p>You would typically want to use both: <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.activate()</a> changes the language for this thread, and setting the cookie makes this preference persist in future requests.
</p>
<div class="versionchanged">
<p>In older versions, you could set the language in the current session.
</p><p><br />
</p>
</div>
</div>
<div id="using-translations-outside-views-and-templates" class="section">
<h3><span class="mw-headline" id="Using_translations_outside_views_and_templates">Using translations outside views and templates</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="59">Using translations outside views and templates</mw:editsection></h3>
<p>While Django provides a rich set of i18n tools for use in views and templates, it does not restrict the usage to Django-specific code. The Django translation mechanisms can be used to translate arbitrary texts to any language that is supported by Django (as long as an appropriate translation catalog exists, of course). You can load a translation catalog, activate it and translate text to language of your choice, but remember to switch back to original language, as activating a translation catalog is done on per-thread basis and such change will affect code running in the same thread.
</p><p>For example:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.utils import translation

def welcome_translated(language):
    cur_language = translation.get_language()
    try:
        translation.activate(language)
        text = translation.gettext('welcome')
    finally:
        translation.activate(cur_language)
    return text</code></pre>
</div>
</div>
<p>Calling this function with the value <code>'de'</code> will give you <code>"Willkommen"</code>, regardless of <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a> and language set by middleware.
</p><p>Functions of particular interest are <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.get_language()</a> which returns the language used in the current thread, <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.activate()</a> which activates a translation catalog for the current thread, and <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.check_for_language()</a> which checks if the given language is supported by Django.
</p><p>To help write more concise code, there is also a context manager <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">django.utils.translation.override()</a> that stores the current language on enter and restores it on exit. With it, the above example becomes:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.utils import translation

def welcome_translated(language):
    with translation.override(language):
        return translation.gettext('welcome')</code></pre>
</div>
</div>
</div>
<div id="language-cookie" class="section">
<h3><span class="mw-headline" id="Language_cookie">Language cookie</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="60">Language cookie</mw:editsection></h3>
<p>A number of settings can be used to adjust language cookie options:
</p>
<ul><li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_NAME" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_NAME</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_AGE" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_AGE</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_DOMAIN" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_DOMAIN</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_HTTPONLY" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_HTTPONLY</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_PATH" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_PATH</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_SAMESITE" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_SAMESITE</code></a></li>
<li><a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_SECURE" title="Django/docs/3.0.x/ref/settings"><code> LANGUAGE_COOKIE_SECURE</code></a></li></ul>
<p><br />
</p>
</div>
</div>
<div id="implementation-notes" class="section">
<h2><span class="mw-headline" id="Implementation_notes">Implementation notes</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="61">Implementation notes</mw:editsection></h2>
<div id="specialties-of-django-translation" class="section">
<p><span id="specialties-of-django-i18n"></span>
</p>
<h3><span class="mw-headline" id="Specialties_of_Django_translation">Specialties of Django translation</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="62">Specialties of Django translation</mw:editsection></h3>
<p>Django’s translation machinery uses the standard <code>gettext</code> module that comes with Python. If you know <code>gettext</code>, you might note these specialties in the way Django does translation:
</p>
<ul><li>The string domain is <code>django</code> or <code>djangojs</code>. This string domain is used to differentiate between different programs that store their data in a common message-file library (usually <code>/usr/share/locale/</code>). The <code>django</code> domain is used for Python and template translation strings and is loaded into the global translation catalogs. The <code>djangojs</code> domain is only used for JavaScript translation catalogs to make sure that those are as small as possible.</li>
<li>Django doesn’t use <code>xgettext</code> alone. It uses Python wrappers around <code>xgettext</code> and <code>msgfmt</code>. This is mostly for convenience.</li></ul>
<p><br />
</p>
</div>
<div id="how-django-discovers-language-preference" class="section">
<p><span id="id5"></span>
</p>
<h3><span class="mw-headline" id="How_Django_discovers_language_preference">How Django discovers language preference</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="63">How Django discovers language preference</mw:editsection></h3>
<p>Once you’ve prepared your translations – or, if you want to use the translations that come with Django – you’ll need to activate translation for your app.
</p><p>Behind the scenes, Django has a very flexible model of deciding which language should be used – installation-wide, for a particular user, or both.
</p><p>To set an installation-wide language preference, set <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a>. Django uses this language as the default translation – the final attempt if no better matching translation is found through one of the methods employed by the locale middleware (see below).
</p><p>If all you want is to run Django with your native language all you need to do is set <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a> and make sure the corresponding <a href="/Django/docs/3.0.x/topics/i18n/index#term-message-file" title="Django/docs/3.0.x/topics/i18n/index">message files</a> and their compiled versions (<code>.mo</code>) exist.
</p><p>If you want to let each individual user specify which language they prefer, then you also need to use the <code>LocaleMiddleware</code>. <code>LocaleMiddleware</code> enables language selection based on data from the request. It customizes content for each user.
</p><p>To use <code>LocaleMiddleware</code>, add <code>'django.middleware.locale.LocaleMiddleware'</code> to your <a href="/Django/docs/3.0.x/ref/settings#std-setting-MIDDLEWARE" title="Django/docs/3.0.x/ref/settings">MIDDLEWARE</a> setting. Because middleware order matters, follow these guidelines:
</p>
<ul><li>Make sure it’s one of the first middleware installed.</li>
<li>It should come after <code>SessionMiddleware</code>, because <code>LocaleMiddleware</code> makes use of session data. And it should come before <code>CommonMiddleware</code> because <code>CommonMiddleware</code> needs an activated language in order to resolve the requested URL.</li>
<li>If you use <code>CacheMiddleware</code>, put <code>LocaleMiddleware</code> after it.</li></ul>
<p>For example, your <a href="/Django/docs/3.0.x/ref/settings#std-setting-MIDDLEWARE" title="Django/docs/3.0.x/ref/settings">MIDDLEWARE</a> might look like this:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">MIDDLEWARE = [
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.locale.LocaleMiddleware',
   'django.middleware.common.CommonMiddleware',
]</code></pre>
</div>
</div>
<p>(For more on middleware, see the <a href="/Django/docs/3.0.x/topics/http/middleware" title="Django/docs/3.0.x/topics/http/middleware">middleware documentation</a>.)
</p><p><code>LocaleMiddleware</code> tries to determine the user’s language preference by following this algorithm:
</p>
<ul>
<li><p>First, it looks for the language prefix in the requested URL. This is only performed when you are using the <code>i18n_patterns</code> function in your root URLconf. See <a href="#url-internationalization">Internationalization: in URL patterns</a> for more information about the language prefix and how to internationalize URL patterns.</p></li>
<li><p>Failing that, it looks for a cookie.</p>
<p>The name of the cookie used is set by the <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_COOKIE_NAME" title="Django/docs/3.0.x/ref/settings">LANGUAGE_COOKIE_NAME</a> setting. (The default name is <code>django_language</code>.)</p></li>
<li><p>Failing that, it looks at the <code>Accept-Language</code> HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations.</p></li>
<li><p>Failing that, it uses the global <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a> setting.</p></li></ul>
<p>Notes:
</p>
<ul>
<li><p>In each of these places, the language preference is expected to be in the standard <a href="/Django/docs/3.0.x/topics/i18n/index#term-language-code" title="Django/docs/3.0.x/topics/i18n/index">language format</a>, as a string. For example, Brazilian Portuguese is <code>pt-br</code>.</p></li>
<li><p>If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies <code>de-at</code> (Austrian German) but Django only has <code>de</code> available, Django uses <code>de</code>.</p></li>
<li><p>Only languages listed in the <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGES" title="Django/docs/3.0.x/ref/settings">LANGUAGES</a> setting can be selected. If you want to restrict the language selection to a subset of provided languages (because your application doesn’t provide all those languages), set <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGES" title="Django/docs/3.0.x/ref/settings">LANGUAGES</a> to a list of languages. For example:</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">LANGUAGES = [
  ('de', _('German')),
  ('en', _('English')),
]</code></pre>
</div>
</div>
<p>This example restricts languages that are available for automatic selection to German and English (and any sublanguage, like <code>de-ch</code> or <code>en-us</code>).</p></li>
<li><p>If you define a custom <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGES" title="Django/docs/3.0.x/ref/settings">LANGUAGES</a> setting, as explained in the previous bullet, you can mark the language names as translation strings – but use <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">gettext_lazy()</a> instead of <a href="/Django/docs/3.0.x/ref/utils#django.utils.translation" title="Django/docs/3.0.x/ref/utils">gettext()</a> to avoid a circular import.</p>
<p>Here’s a sample settings file:</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.utils.translation import gettext_lazy as _

LANGUAGES = [
    ('de', _('German')),
    ('en', _('English')),
]</code></pre>
</div>
</div></li></ul>
<p>Once <code>LocaleMiddleware</code> determines the user’s preference, it makes this preference available as <code>request.LANGUAGE_CODE</code> for each <a href="/Django/docs/3.0.x/ref/request-response#django.http" title="Django/docs/3.0.x/ref/request-response">HttpRequest</a>. Feel free to read this value in your view code. Here’s an example:
</p>
<div class="highlight-python notranslate">
<div class="highlight">
<pre class="mw-highlight mw-highlight-lang-python" dir="ltr"><code class="language-python">from django.http import HttpResponse

def hello_world(request, count):
    if request.LANGUAGE_CODE == 'de-at':
        return HttpResponse("You prefer to read Austrian German.")
    else:
        return HttpResponse("You prefer to read another language.")</code></pre>
</div>
</div>
<p>Note that, with static (middleware-less) translation, the language is in <code>settings.LANGUAGE_CODE</code>, while with dynamic (middleware) translation, it’s in <code>request.LANGUAGE_CODE</code>.
</p><p><br />
</p>
</div>
<div id="how-django-discovers-translations" class="section">
<p><span id="id6"></span>
</p>
<h3><span class="mw-headline" id="How_Django_discovers_translations">How Django discovers translations</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="64">How Django discovers translations</mw:editsection></h3>
<p>At runtime, Django builds an in-memory unified catalog of literals-translations. To achieve this it looks for translations by following this algorithm regarding the order in which it examines the different file paths to load the compiled <a href="/Django/docs/3.0.x/topics/i18n/index#term-message-file" title="Django/docs/3.0.x/topics/i18n/index">message files</a> (<code>.mo</code>) and the precedence of multiple translations for the same literal:
</p>
<ol><li>The directories listed in <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> have the highest precedence, with the ones appearing first having higher precedence than the ones appearing later.</li>
<li>Then, it looks for and uses if it exists a <code>locale</code> directory in each of the installed apps listed in <a href="/Django/docs/3.0.x/ref/settings#std-setting-INSTALLED_APPS" title="Django/docs/3.0.x/ref/settings">INSTALLED_APPS</a>. The ones appearing first have higher precedence than the ones appearing later.</li>
<li>Finally, the Django-provided base translation in <code>django/conf/locale</code> is used as a fallback.</li></ol>
<div class="admonition seealso">
<p>See also
</p><p>The translations for literals included in JavaScript assets are looked up following a similar but not identical algorithm. See <a href="#django.views.i18n.JavaScriptCatalog">JavaScriptCatalog</a> for more details.
</p><p>You can also put <a href="/Django/docs/3.0.x/topics/i18n/formatting#custom-format-files" title="Django/docs/3.0.x/topics/i18n/formatting">custom format files</a> in the <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> directories if you also set <a href="/Django/docs/3.0.x/ref/settings#std-setting-FORMAT_MODULE_PATH" title="Django/docs/3.0.x/ref/settings">FORMAT_MODULE_PATH</a>.
</p><p><br />
</p>
</div>
<p>In all cases the name of the directory containing the translation is expected to be named using <a href="/Django/docs/3.0.x/topics/i18n/index#term-locale-name" title="Django/docs/3.0.x/topics/i18n/index">locale name</a> notation. E.g. <code>de</code>, <code>pt_BR</code>, <code>es_AR</code>, etc. Untranslated strings for territorial language variants use the translations of the generic language. For example, untranslated <code>pt_BR</code> strings use <code>pt</code> translations.
</p><p>This way, you can write applications that include their own translations, and you can override base translations in your project. Or, you can build a big project out of several apps and put all translations into one big common message file specific to the project you are composing. The choice is yours.
</p><p>All message file repositories are structured the same way. They are:
</p>
<ul><li>All paths listed in <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> in your settings file are searched for <code>/LC_MESSAGES/django.(po|mo)</code></li>
<li><code> $APPPATH/locale//LC_MESSAGES/django.(po|mo)</code></li>
<li><code> $PYTHONPATH/django/conf/locale//LC_MESSAGES/django.(po|mo)</code></li></ul>
<p>To create message files, you use the <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-makemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin makemessages</a> tool. And you use <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin compilemessages</a> to produce the binary <code>.mo</code> files that are used by <code>gettext</code>.
</p><p>You can also run <a href="/Django/docs/3.0.x/ref/django-admin#django-admin-compilemessages" title="Django/docs/3.0.x/ref/django-admin">django-admin compilemessages --settings=path.to.settings</a> to make the compiler process all the directories in your <a href="/Django/docs/3.0.x/ref/settings#std-setting-LOCALE_PATHS" title="Django/docs/3.0.x/ref/settings">LOCALE_PATHS</a> setting.
</p><p><br />
</p>
</div>
<div id="using-a-non-english-base-language" class="section">
<h3><span class="mw-headline" id="Using_a_non-English_base_language">Using a non-English base language</span><mw:editsection page="Django/docs/3.0.x/topics/i18n/translation" section="65">Using a non-English base language</mw:editsection></h3>
<p>Django makes the general assumption that the original strings in a translatable project are written in English. You can choose another language, but you must be aware of certain limitations:
</p>
<ul><li><code>gettext</code> only provides two plural forms for the original messages, so you will also need to provide a translation for the base language to include all plural forms if the plural rules for the base language are different from English.</li>
<li>When an English variant is activated and English strings are missing, the fallback language will not be the <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a> of the project, but the original strings. For example, an English user visiting a site with <a href="/Django/docs/3.0.x/ref/settings#std-setting-LANGUAGE_CODE" title="Django/docs/3.0.x/ref/settings">LANGUAGE_CODE</a> set to Spanish and original strings written in Russian will see Russian text rather than Spanish.</li></ul>
<p><br />
</p>
</div>
</div>
</div>
<div class="clearer">
<p><br />
</p>
</div>