Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 77 ยท Middleware, Signals and Internals

Internationalization and Localization in Depth

Translate a Django site properly: gettext and lazy strings, plurals, template tags, makemessages and compilemessages, LocaleMiddleware, i18n_patterns URLs and localized formats.

The logging, email and internationalization lesson introduced translation in one section. This lesson goes the whole way: how strings get marked, how translators receive them, how Django picks a language for each request, how URLs themselves can be translated, and how numbers and dates adapt to a locale.

Two words are worth keeping apart. Internationalization (i18n) is preparing code so text can be translated. Localization (l10n) is adapting output to a locale: the translation itself plus formats for dates, numbers and so on. Django does both, and the pieces are small once you see how they fit.

The settings

Python
# settings.py (read-only)
USE_I18N = True                        # turn the translation machinery on
LANGUAGE_CODE = "en"                   # fallback language
LANGUAGES = [("en", "English"), ("fr", "Franรงais"), ("es", "Espaรฑol")]
LOCALE_PATHS = [BASE_DIR / "locale"]   # where your translation files live
USE_THOUSAND_SEPARATOR = True          # optional: 1,234,567 / 1 234 567

MIDDLEWARE = [
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",     # after Session, before Common
    "django.middleware.common.CommonMiddleware",
    # ...
]

LANGUAGES is the list of languages your site offers (Django itself ships translations for over a hundred). Requests for other languages fall back to LANGUAGE_CODE. The middleware order matters: LocaleMiddleware needs the session (to remember a choice) and must run before CommonMiddleware so URL prefixes are handled correctly.

Marking strings for translation

You wrap every user-visible string in a translation function. All of them live in django.utils.translation:

Function Use it for
gettext("text") (imported as _) A string that is used during a request, such as in a view
gettext_lazy("text") A string defined at import time: model fields, form labels, verbose_name, URL patterns, class attributes
ngettext("one", "many", n) Plurals ("1 message" vs "3 messages")
pgettext("context", "text") The same English word that translates differently by meaning ("May" the month and "may" the verb)

The rule of thumb: if the code runs when the module is imported, use the lazy version. A plain gettext there would be translated once, in whatever language was active at startup, and never again. In templates use {% trans "Welcome" %} for a simple string and {% blocktranslate %} for text with variables and plurals:

DJANGO
{# read-only #}
{% load i18n %}
<h1>{% trans "Welcome" %}</h1>

{% blocktranslate with name=user.first_name %}Hello, {{ name }}!{% endblocktranslate %}

{% blocktranslate count counter=unread %}
You have {{ counter }} unread message.
{% plural %}
You have {{ counter }} unread messages.
{% endblocktranslate %}

Never build a translatable string with an f-string or +: _(f"Hello {name}") cannot be extracted because the text changes at run time. Use placeholders: _("Hello, %(name)s!") % {"name": name}. Translators can then move the placeholder to wherever their grammar needs it.

The translation workflow

On your own machine (GNU gettext must be installed), translation is a short loop:

Terminal
# read-only
python manage.py makemessages -l fr -l es      # scan code/templates, create or update .po files
# ... a translator fills in msgstr entries in locale/fr/LC_MESSAGES/django.po ...
python manage.py compilemessages               # turn .po files into binary .mo files

makemessages writes a .po file, a text catalog that translators (or tools such as Weblate and Crowdin) can edit:

PO
# locale/fr/LC_MESSAGES/django.po (read-only)
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#: shop/views.py:12
msgid "Welcome"
msgstr "Bienvenue"

#: shop/templates/shop/inbox.html:4
#, python-format
msgid "You have %(count)d message"
msgid_plural "You have %(count)d messages"
msgstr[0] "Vous avez %(count)d message"
msgstr[1] "Vous avez %(count)d messages"

msgctxt "month"
msgid "May"
msgstr "mai"

Entries marked #, fuzzy are guesses that Django ignores until a human removes the flag. Re-run makemessages whenever you add text; existing translations are kept. The plural rule in the header differs per language (Polish has three forms, Arabic six), which is why you always write ngettext instead of "add an s".

compilemessages produces the .mo file that Django actually reads. The browser cannot run GNU gettext, but the .mo format is simple, so the first example writes a small catalog with a few lines of Python. That shows exactly what the tool outputs, and then Django loads it like a real project's file.

Python Build a catalog, then translate with gettext, ngettext and templates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Watch three things. es has no plural entry, and de has no catalog at all, so both fall back to the English source text: an untranslated string is never an error, it just shows in the original language. The lazy GREETING followed each active language while the eager EAGER stayed fixed. And pgettext gave the month and the verb different French words for the same English "May", which is what the context argument is for. The template rendered the plural form correctly for 4 and for 1 because the catalog's Plural-Forms rule picks the form.

Choosing the language for each request

LocaleMiddleware decides the active language for every request. It checks, in this order:

  1. the language prefix in the URL (/fr/...) when you use i18n_patterns,
  2. the language cookie (django_language, set by the set_language view),
  3. the browser's Accept-Language header,
  4. LANGUAGE_CODE.

It then stores the result on request.LANGUAGE_CODE and sends Content-Language and Vary: Accept-Language (so caches keep versions apart). Choosing by URL is the best option for public sites: every language has its own address, which search engines can index and users can share.

i18n_patterns and translated URLs

i18n_patterns wraps your URL patterns in a language prefix. Using gettext_lazy for a path segment even translates the URL itself (/fr/a-propos/). Use reverse() and {% url %} as always, and they build the URL in the active language.

Python LocaleMiddleware and i18n_patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first block shows the detection order at work: a bare / redirects to the best match (Accept-Language, then the cookie), falling back to English for a language the site does not offer. /fr/about/ is a 404 because in French the path segment is a-propos. The second block shows localization: the same date and number print as March 5, 2026 and 1,234,567.5 in English, 5 mars 2026 and 1 234 567,5 in French, and Spanish gets its own forms. Django's built-in format definitions supply this, so you do not format anything by hand.

Letting users switch language

Django ships a set_language view. A small form posts the chosen language plus the page to return to; the view stores the choice in the django_language cookie and redirects:

DJANGO
{# read-only #}
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">
  {% csrf_token %}
  <input name="next" type="hidden" value="{{ redirect_to }}">
  <select name="language" onchange="this.form.submit()">
    {% get_current_language as CURRENT %}
    {% get_available_languages as LANGUAGES %}
    {% for code, name in LANGUAGES %}
      <option value="{{ code }}" {% if code == CURRENT %}selected{% endif %}>{{ name }}</option>
    {% endfor %}
  </select>
</form>

With i18n_patterns, set next to the translated URL (use translate_url() or {% language code %}{% url ... %}{% endlanguage %}) so users land on the same page in the new language.

Localized formats

When USE_I18N is on, Django formats dates, times, numbers and decimals according to the active language automatically in templates. Some tools to remember:

  • {{ value|date:"DATE_FORMAT" }} and "SHORT_DATE_FORMAT" use the locale's format names instead of a hard-coded pattern. A literal pattern like "Y-m-d" is fixed on purpose.
  • {% load l10n %} with {{ value|localize }} or {{ value|unlocalize }} forces or disables localization for one value. Use unlocalize when printing numbers into JavaScript or HTML attributes, where 1 234,5 would break the code.
  • USE_THOUSAND_SEPARATOR = True turns on grouping digits; the character and the group size come from the locale.
  • Forms parse input with the active locale too: a French user can type 12,5 into a DecimalField.
  • Customize or add formats with FORMAT_MODULE_PATH, a package that provides a formats.py per locale.

Practical advice

  • Right-to-left languages (Arabic, Hebrew) need dir="rtl". Use {% get_current_language_bidi as bidi %} and <html dir="{% if bidi %}rtl{% else %}ltr{% endif %}">, and write CSS with logical properties (margin-inline-start).
  • Do not translate user data with gettext. Product names and blog posts that users write live in the database. Use a dedicated package (such as django-modeltranslation or django-parler) or separate fields per language.
  • Keep sentences whole. Translating fragments ("You have" and "messages" as two strings) cannot be reordered in other languages.
  • Add translator comments. # Translators: shown on the checkout button above the call becomes a note in the .po file.
  • Test it. Run key views inside translation.override("fr"), and add a CI step that runs makemessages and compilemessages to catch broken placeholders (the compiler validates format strings).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must you use gettext_lazy instead of gettext?

    At import time no request has chosen a language. A lazy string defers the lookup until it is displayed, so it follows the active language.
  2. 2. What file does Django actually read at run time for translations?

    makemessages creates editable .po files; compilemessages turns them into binary .mo files that Django loads.
  3. 3. Why is _(f'Hello {name}') a mistake?

    makemessages reads source code and needs a fixed msgid. Placeholders also let translators reorder the words.
  4. 4. What does LocaleMiddleware check first when choosing the language?

    The order is URL prefix, cookie, Accept-Language, then LANGUAGE_CODE.

Summary

  • Mark text with gettext, gettext_lazy (for import-time code), ngettext for plurals and pgettext for context; use {% trans %} and {% blocktranslate %} in templates.
  • makemessages extracts strings into .po files, translators fill them in, and compilemessages builds the .mo files Django loads; missing translations fall back to the source language.
  • LocaleMiddleware picks the language from the URL prefix, cookie, Accept-Language or LANGUAGE_CODE; i18n_patterns and lazy path segments give each language its own URLs.
  • Dates, numbers and form input are localized automatically; use unlocalize for machine-readable output.
  • Keep sentences whole, use placeholders, handle right-to-left layout, and translate user-generated data with a model-translation package.

Next: Sitemaps, RSS Feeds and robots.txt.