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
| Piece | Role |
|---|---|
gettext / _ | Eager translate |
gettext_lazy / gettext_noop | Lazy / mark only |
ngettext | Plurals |
LocaleMiddleware | Per-request language |
LANGUAGE_CODE / LANGUAGES | Defaults / available |
USE_I18N / USE_L10N | Feature flags (L10N always on in 5.0+) |
makemessages | Build .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 modelverbose_name—prefer_lazy. - Interpolating before translating breaks message catalogs.
- Missing
LocaleMiddlewareorder (after Session, before Common). - Forgetting to compile
.moin deploy. - Hardcoded date formats—use
localize/datefilters.