from django.utils.translation import gettext_lazy as _
LANGUAGE_CODE = 'en-us'
LANGUAGES = [
('en', _('English')),
('es', _('Spanish')),
('fr', _('French')),
('de', _('German')),
]
LOCALE_PATHS = [BASE_DIR / 'locale']
USE_I18N = True
USE_L10N = True
USE_TZ = True
MIDDLEWARE += ['django.middleware.locale.LocaleMiddleware']
from django.utils.translation import gettext as _
from django.http import JsonResponse
def my_view(request):
message = _('Welcome to our site!')
error = _('An error occurred.')
return JsonResponse({
'message': message,
'error': error
})
{% load i18n %}
<h1>{% trans "Welcome" %}</h1>
{% blocktrans count counter=items|length %}
There is {{ counter }} item.
{% plural %}
There are {{ counter }} items.
{% endblocktrans %}
<p>{% trans "Change language:" %}</p>
<a href="/en/">English</a> |
<a href="/es/">EspaƱol</a>
Django's i18n framework supports multiple languages. I mark strings for translation with gettext() or _(). The makemessages command extracts strings to .po files. Translators fill in translations, then compilemessages creates binary .mo files. I use {% trans %} and {% blocktrans %} in templates. The LocaleMiddleware sets language from URL prefix, cookie, or Accept header. For dates and numbers, I use l10n formatting. This enables global reach without code duplication per language.