Code Reference

i18n

Django · Reference cheat sheet

i18n

Django · Reference cheat sheet


📋 Overview

Internationalization (i18n) marks strings for translation; localization (l10n) formats dates, numbers, and timezones. Use gettext / gettext_lazy, \{% translate %\}, and makemessages / compilemessages. Activate languages via middleware, URLs, or explicit activate().

🔧 Core concepts

PieceRole
gettext / _Eager translate
gettext_lazy / gettext_noopLazy / mark only
ngettextPlurals
LocaleMiddlewarePer-request language
LANGUAGE_CODE / LANGUAGESDefaults / available
USE_I18N / USE_L10NFeature flags (L10N always on in 5.0+)
makemessagesBuild .po
compilemessages.po.mo

Timezone: USE_TZ = True, timezone.now(), activate user TZ in middleware.

💡 Examples

Python:

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


class Article(models.Model):
    title = models.CharField(_lazy("Title"), max_length=200)


def greet(name: str) -> str:
    return _("Hello, %(name)s") % {"name": name}

Template:

{% load i18n %}
{% translate "Welcome" %}
{% blocktranslate count counter=items|length %}
  One item
{% plural %}
  {{ counter }} items
{% endblocktranslate %}
<form action="{% url 'set_language' %}" method="post">
  {% csrf_token %}
  <input name="language" value="es">
  <button type="submit">ES</button>
</form>

Commands / settings:

LANGUAGE_CODE = "en-us"
LANGUAGES = [("en", "English"), ("es", "Spanish")]
LOCALE_PATHS = [BASE_DIR / "locale"]
MIDDLEWARE = [
    ...
    "django.middleware.locale.LocaleMiddleware",
    ...
]
django-admin makemessages -l es
django-admin compilemessages

⚠️ Pitfalls

  • Using _() at module import for model verbose_name—prefer _lazy.
  • Interpolating before translating breaks message catalogs.
  • Missing LocaleMiddleware order (after Session, before Common).
  • Forgetting to compile .mo in deploy.
  • Hardcoded date formats—use localize / date filters.

On this page