Django internationalization
last modified November 21, 2026 Python 3.15
A site with visitors from several countries should speak their language and show numbers, dates, and times the way they are used to. Django prepares an application for this with the internationalization (i18n) tools: the developer marks the texts that need translation, and Django picks the language of each request. The localization (l10n) is the work for a particular language: the translations and the formats. In this article we translate a small shop into Slovak, a language with more plural forms than English, look at lazy translation, templates, and formats, put the language into the URL, add a language switcher, show the times in the zone of the visitor, and test the result. The examples use Django 6.1 and Python 3.15.
How translation works
Django uses GNU gettext, the standard system of the free software world. In the code a text is wrapped in a call to a function such as
gettext(), usually imported as _. The command makemessages scans the source files for these calls and
writes the texts, called message ids, into a .po file per language, where a translator fills in the translations. The
command compilemessages turns the file into a binary .mo file, which Django loads at run time. When a request is
processed, the middleware LocaleMiddleware activates a language, and every call to gettext() looks up the message id
in the catalog of that language; a text without a translation stays as it is.
The example project
The project is created with uv; the steps are explained in
Django introduction. The commands below create a project
directory, install Django, generate the project with the configuration package
config, start the app catalog, and create the folder demos for demo scripts.
$ mkdir i18n $ cd i18n $ uv init --bare $ uv add django $ uv run django-admin startproject config . $ uv run python manage.py startapp catalog $ mkdir demos $ mkdir locale
The trailing dot in startproject config . creates manage.py and the
config package in the current directory instead of one level deeper. A new app is
ignored by Django until it is listed in INSTALLED_APPS, so we add
the app to the list in config/settings.py; the other
entries are generated by startproject.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catalog',
]
The listings in this article are of two kinds. A listing with a solid blue border and the label
Project file is a file of the application: models, views, templates, tests, and
settings. A listing with a dashed amber border and the label Demo script is a small
helper in the demos folder; it sets up Django, runs a few lines of code, and prints
the results, so that we can watch the behaviour. Demo scripts are not part of the application;
we run one from the project directory with uv run python -m demos.name.
The folder locale created by the last command will hold the translation files. The commands makemessages and
compilemessages call the gettext tools xgettext, msgmerge, and msgfmt, which are not part
of Python. On Debian and Ubuntu they are in the package gettext (sudo apt install gettext), on macOS in Homebrew's
gettext. We check that they are available.
$ msgfmt --version | head -n 1 msgfmt (GNU gettext-tools) 0.21
The settings of the language go to config/settings.py. LANGUAGES limits the languages that the site offers;
without it Django would accept any of the 100 languages in its default list. The names are marked for translation with
gettext_lazy, explained later, so that the language switcher shows them in the current language. LANGUAGE_CODE
is the fallback for visitors whose language is not offered, and LOCALE_PATHS tells Django where to look for our translation
files. LocaleMiddleware chooses the language of a request; it must come after SessionMiddleware and before
CommonMiddleware. USE_I18N, USE_TZ, and TIME_ZONE keep the values generated by
startproject.
from pathlib import Path
from django.utils.translation import gettext_lazy as _
...
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
...
LANGUAGE_CODE = 'en'
LANGUAGES = [
('en', _('English')),
('sk', _('Slovak')),
]
LOCALE_PATHS = [BASE_DIR / 'locale']
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
With these settings in place we can start marking texts.
Marking strings in Python code
The first view returns a single sentence. The function gettext() is imported under the name _, which is the
convention of gettext and the name that makemessages looks for, together with the full names of the functions.
from django.http import HttpResponse
from django.utils.translation import gettext as _
def welcome(request):
return HttpResponse(_('Welcome to our shop'))
The app gets its own URL configuration with a single path.
from django.urls import path
from . import views
urlpatterns = [
path('welcome/', views.welcome),
]
The project includes the URLs of the app at the root.
from django.urls import include, path
urlpatterns = [
path('', include('catalog.urls')),
]
The demo script sends requests with different Accept-Language headers, which browsers fill from the language preferences of the
user, and prints the header, the language of the response, and the text. The function setup_test_environment() prepares Django
for the test client.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.test import Client
from django.test.utils import setup_test_environment
setup_test_environment()
client = Client()
for header in ['en-US,en;q=0.9', 'sk', 'de-DE,de;q=0.9,sk;q=0.8', 'fr-FR', '']:
response = client.get('/welcome/', headers={'Accept-Language': header})
language = response['Content-Language']
print(f'{header!r:28} {language:3} {response.content.decode()}')
LocaleMiddleware already picks the right language and puts it into the header Content-Language. A visitor who prefers
German and then Slovak gets Slovak, because German is not in LANGUAGES; French and an empty header fall back to English. The text
is English everywhere because there is no translation yet. Besides the header, the middleware looks at the language prefix in the URL and at
the cookie django_language, which take precedence; we use both later.
$ uv run python -m demos.welcome 'en-US,en;q=0.9' en Welcome to our shop 'sk' sk Welcome to our shop 'de-DE,de;q=0.9,sk;q=0.8' sk Welcome to our shop 'fr-FR' en Welcome to our shop '' en Welcome to our shop
Translation files
The command makemessages -l sk creates or updates the Slovak catalog. It scans the Python files and the templates of the project;
the option --ignore demos leaves out the demo scripts, whose texts do not belong to the shop. Folders whose names start with a dot,
such as .venv, are skipped by default. The file goes to the first directory of LOCALE_PATHS.
$ uv run python manage.py makemessages -l sk --ignore demos
processing locale sk
$ tree locale
locale
└── sk
└── LC_MESSAGES
└── django.po
2 directories, 1 file
A .po file is a plain text file. It starts with a header whose Plural-Forms line Django has taken from its own Slovak
translation. Each entry has comments with the places where the text occurs, the message id, and the translation in msgstr. We fill
in the translations and the header fields and remove the line #, fuzzy that the generated header has, since msgfmt skips
fuzzy entries. The two language names come from settings.py.
# Slovak translation of the shop. msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-11-21 16:13+0000\n" "PO-Revision-Date: 2026-11-21 10:00+0100\n" "Last-Translator: Jan Bodnar\n" "Language-Team: Slovak\n" "Language: sk\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n % 1 == 0 && n == 1 ? 0 : n % 1 == 0 && n " ">= 2 && n <= 4 ? 1 : n % 1 != 0 ? 2: 3);\n" #: catalog/views.py:6 msgid "Welcome to our shop" msgstr "Vitajte v našom obchode" #: config/settings.py:112 msgid "English" msgstr "Angličtina" #: config/settings.py:113 msgid "Slovak" msgstr "Slovenčina"
The command compilemessages compiles every .po file below the current directory into a .mo file next to
it. The option --ignore .venv is important in a uv project: unlike makemessages, this command does not skip the hidden
folders, and without the option it also walks through the virtual environment and recompiles the catalogs of Django and of other installed
packages, more than 1200 lines of output in our project.
$ uv run python manage.py compilemessages --ignore .venv
processing file django.po in ./locale/sk/LC_MESSAGES
$ tree locale
locale
└── sk
└── LC_MESSAGES
├── django.mo
└── django.po
2 directories, 2 files
Django caches the loaded catalogs in the process. The development server clears the cache when a .mo file changes, but a
production server must be restarted after compilemessages. The demo now gets the Slovak text for the visitors who prefer Slovak.
$ uv run python -m demos.welcome 'en-US,en;q=0.9' en Welcome to our shop 'sk' sk Vitajte v našom obchode 'de-DE,de;q=0.9,sk;q=0.8' sk Vitajte v našom obchode 'fr-FR' en Welcome to our shop '' en Welcome to our shop
Plural forms and contexts
Sentences with a number cannot be translated with a simple lookup, because languages have different numbers of plural forms. English has two;
Slovak uses one form for 1, another for 2 to 4, a third for 5 and more, and a fourth for fractions. The function ngettext() takes the
singular, the English plural, and the number, and chooses the form of the active language. The number is inserted with a named placeholder, so
that a translator can move it to any place in the sentence.
from django.http import HttpResponse
from django.utils.translation import gettext as _
from django.utils.translation import ngettext, pgettext
def welcome(request):
return HttpResponse(_('Welcome to our shop'))
def cart(request, count):
text = ngettext(
'There is %(count)d product in the cart.',
'There are %(count)d products in the cart.',
count,
) % {'count': count}
return HttpResponse(text)
def sign(request):
# Translators: the sign on the door says that the shop is open
status = pgettext('door sign', 'Open')
# Translators: a button that opens the shopping cart
action = pgettext('button', 'Open')
return HttpResponse(f'{status} | {action}')
The same English word can need different translations. The function pgettext() adds a context, which makes the two
Open texts separate entries. A comment that starts with Translators: directly above the call is copied to the catalog as a
hint for the translator. The URL configuration of the app gets the two new paths.
from django.urls import path
from . import views
urlpatterns = [
path('welcome/', views.welcome),
path('cart/<int:count>/', views.cart),
path('sign/', views.sign),
]
We run makemessages again. It keeps the existing translations and adds the new entries, which we translate. The plural entry has
four msgstr lines, one for each form of the Plural-Forms formula; the flag python-format tells
msgfmt to check that the translations keep the placeholders. Then we compile the catalog.
$ uv run python manage.py makemessages -l sk --ignore demos processing locale sk
#: catalog/views.py:12 #, python-format msgid "There is %(count)d product in the cart." msgid_plural "There are %(count)d products in the cart." msgstr[0] "V košíku je %(count)d produkt." msgstr[1] "V košíku sú %(count)d produkty." msgstr[2] "V košíku je %(count)d produktu." msgstr[3] "V košíku je %(count)d produktov." #. Translators: the sign on the door says that the shop is open #: catalog/views.py:21 msgctxt "door sign" msgid "Open" msgstr "Otvorené" #. Translators: a button that opens the shopping cart #: catalog/views.py:23 msgctxt "button" msgid "Open" msgstr "Otvoriť"
The compilation reports only our catalog.
$ uv run python manage.py compilemessages --ignore .venv processing file django.po in ./locale/sk/LC_MESSAGES
The demo script asks for carts of several sizes and for the sign in both languages.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.test import Client
from django.test.utils import setup_test_environment
setup_test_environment()
client = Client()
for language in ['en', 'sk']:
for count in [1, 2, 4, 5, 21]:
response = client.get(f'/cart/{count}/', headers={'Accept-Language': language})
print(language, response.content.decode())
response = client.get('/sign/', headers={'Accept-Language': language})
print(language, response.content.decode())
English uses the singular only for one product. In Slovak the forms change at 2 and at 5, and 21 uses the form for five and more, as the formula of the Slovak header says. The two Open texts have different translations.
$ uv run python -m demos.plurals en There is 1 product in the cart. en There are 2 products in the cart. en There are 4 products in the cart. en There are 5 products in the cart. en There are 21 products in the cart. en Open | Open sk V košíku je 1 produkt. sk V košíku sú 2 produkty. sk V košíku sú 4 produkty. sk V košíku je 5 produktov. sk V košíku je 21 produktov. sk Otvorené | Otvoriť
Lazy translation
The function gettext() translates when it is called, into the language that is active at that moment. That is right inside a view,
but wrong for texts that are evaluated when a module is imported, such as the names of model fields, the labels of form fields, or the
LANGUAGES setting: at import time no request is being processed, and the text would be fixed in the default language forever. The
function gettext_lazy() returns a proxy object that is translated each time it is converted to a string. The model of a product uses it
for the verbose names of the fields and of the model, which the admin and the model forms display.
from django.db import models
from django.utils.translation import gettext_lazy as _
class Product(models.Model):
name = models.CharField(_('name'), max_length=60)
price = models.DecimalField(_('price'), max_digits=8, decimal_places=2)
added = models.DateTimeField(_('added'))
class Meta:
verbose_name = _('product')
verbose_name_plural = _('products')
ordering = ['name']
def __str__(self):
return self.name
We create the table and add three products with the script seed.py. The times are stored in UTC.
$ uv run python manage.py makemigrations catalog
Migrations for 'catalog':
catalog/migrations/0001_initial.py
+ Create model Product
$ uv run python manage.py migrate | tail -n 2
Applying catalog.0001_initial... OK
Applying sessions.0001_initial... OK
import os
from datetime import UTC, datetime
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from catalog.models import Product
Product.objects.all().delete()
Product.objects.create(name='Coffee mug', price='12.90',
added=datetime(2026, 11, 20, 14, 30, tzinfo=UTC))
Product.objects.create(name='Desk lamp', price='1249.00',
added=datetime(2026, 11, 21, 8, 5, tzinfo=UTC))
Product.objects.create(name='Notebook', price='4.50',
added=datetime(2026, 11, 21, 23, 45, tzinfo=UTC))
print('products:', Product.objects.count())
The script deletes the existing products first, so it can be run again.
$ uv run python -m demos.seed products: 3
The new texts of the model are added to the catalog and translated.
#: catalog/models.py:6 msgid "name" msgstr "názov" #: catalog/models.py:7 msgid "price" msgstr "cena" #: catalog/models.py:8 msgid "added" msgstr "pridaný" #: catalog/models.py:11 msgid "product" msgstr "produkt" #: catalog/models.py:12 msgid "products" msgstr "produkty"
After running makemessages, translating, and compilemessages as before, the demo script compares an eager and a lazy
translation of the same word, both created at import time in English.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.utils import translation
from django.utils.translation import gettext, gettext_lazy
from catalog.models import Product
eager = gettext('price')
lazy = gettext_lazy('price')
print('type of lazy:', type(lazy).__name__)
for language in ['en', 'sk']:
with translation.override(language):
meta = Product._meta
fields = [str(meta.get_field(name).verbose_name) for name in ('name', 'price', 'added')]
print(f'{language}: {meta.verbose_name}, {meta.verbose_name_plural}, {fields}')
print(f'{language}: eager={eager}, lazy={lazy}')
The lazy object is a __proxy__ that follows the active language, while the eager text stays English. The verbose names of the model
are translated in the Slovak block. A lazy object cannot be used everywhere a string can; it must be converted with str() before it is,
for example, passed to json.dumps().
$ uv run python -m demos.lazy type of lazy: __proxy__ en: product, products, ['name', 'price', 'added'] en: eager=price, lazy=price sk: produkt, produkty, ['názov', 'cena', 'pridaný'] sk: eager=price, lazy=cena
Templates
The view products renders a list of the products. It passes the verbose names of three fields, which are lazy objects, so the
template can use them as column headers.
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import gettext as _
from django.utils.translation import ngettext, pgettext
from .models import Product
def welcome(request):
return HttpResponse(_('Welcome to our shop'))
def cart(request, count):
text = ngettext(
'There is %(count)d product in the cart.',
'There are %(count)d products in the cart.',
count,
) % {'count': count}
return HttpResponse(text)
def sign(request):
# Translators: the sign on the door says that the shop is open
status = pgettext('door sign', 'Open')
# Translators: a button that opens the shopping cart
action = pgettext('button', 'Open')
return HttpResponse(f'{status} | {action}')
def products(request):
fields = [Product._meta.get_field(name).verbose_name for name in ('name', 'price', 'added')]
context = {'products': Product.objects.all(), 'fields': fields}
return render(request, 'catalog/products.html', context)
The new path has a name, so that it can be reversed.
from django.urls import path
from . import views
urlpatterns = [
path('welcome/', views.welcome),
path('cart/<int:count>/', views.cart),
path('sign/', views.sign),
path('products/', views.products, name='products'),
]
Templates load the tag library i18n. The tag {% translate %} translates a constant text, and
{% blocktranslate %} a text with variables; with count it selects a plural form, and {% plural %} separates
the singular from the plural. Inside the block only simple variables can be used, so the length of the list is bound to counter.
{% get_current_language %} stores the code of the active language in a variable, which goes to the attribute lang
of the page.
{% load i18n %}
<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8">
<title>{% translate "Our products" %}</title>
</head>
<body>
<h1>{% translate "Our products" %}</h1>
<p>
{% blocktranslate count counter=products|length %}We sell {{ counter }} product.{% plural %}We sell {{ counter }} products.{% endblocktranslate %}
</p>
<table>
<tr>{% for field in fields %}<th>{{ field|capfirst }}</th>{% endfor %}</tr>
{% for product in products %}
<tr><td>{{ product.name }}</td><td>{{ product.price }}</td><td>{{ product.added }}</td></tr>
{% endfor %}
</table>
</body>
</html>
After makemessages the new entries look like this. The command did not leave them empty: msgmerge found similar texts
in the catalog and copied their translations as a guess, marked with the flag fuzzy and the previous message id in the
#| comments. The guesses are wrong here; the plural even has other placeholders. Fuzzy entries are not compiled, so a wrong guess
never reaches the site, but each one must be reviewed.
$ uv run python manage.py makemessages -l sk --ignore demos processing locale sk
#: catalog/templates/catalog/products.html:7 #: catalog/templates/catalog/products.html:10 #, fuzzy #| msgid "products" msgid "Our products" msgstr "produkty" #: catalog/templates/catalog/products.html:12 #, fuzzy, python-format #| msgid "There is %(count)d product in the cart." #| msgid_plural "There are %(count)d products in the cart." msgid "We sell %(counter)s product." msgid_plural "We sell %(counter)s products." msgstr[0] "V košíku je %(count)d produkt." msgstr[1] "V košíku sú %(count)d produkty." msgstr[2] "V košíku je %(count)d produktu." msgstr[3] "V košíku je %(count)d produktov."
We write the correct translations and remove the flags and the old ids, which leaves the entries below, and compile the catalog. The template
placeholder is %(counter)s, named after the variable of {% blocktranslate %}.
#: catalog/templates/catalog/products.html:7 #: catalog/templates/catalog/products.html:10 msgid "Our products" msgstr "Naše produkty" #: catalog/templates/catalog/products.html:12 #, python-format msgid "We sell %(counter)s product." msgid_plural "We sell %(counter)s products." msgstr[0] "Predávame %(counter)s produkt." msgstr[1] "Predávame %(counter)s produkty." msgstr[2] "Predávame %(counter)s produktu." msgstr[3] "Predávame %(counter)s produktov."
The compiled catalog is ready for the server.
$ uv run python manage.py compilemessages --ignore .venv processing file django.po in ./locale/sk/LC_MESSAGES
We start the development server and request the page from another terminal.
$ uv run python manage.py runserver
The command grep -v '^$' removes the empty lines that the template tags leave behind. Besides the texts, the format of the values
has changed: the prices have a decimal comma in Slovak, and the dates follow the Slovak format, with the name of the month translated by Django.
The names of the products are data, not texts of the program, so gettext does not translate them; that would need a translated column in the
database.
$ curl -s -H 'Accept-Language: en' localhost:8000/products/ | grep -v '^$' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Our products</title> </head> <body> <h1>Our products</h1> <p> We sell 3 products. </p> <table> <tr><th>Name</th><th>Price</th><th>Added</th></tr> <tr><td>Coffee mug</td><td>12.90</td><td>Nov. 20, 2026, 2:30 p.m.</td></tr> <tr><td>Desk lamp</td><td>1249.00</td><td>Nov. 21, 2026, 8:05 a.m.</td></tr> <tr><td>Notebook</td><td>4.50</td><td>Nov. 21, 2026, 11:45 p.m.</td></tr> </table> </body> </html> $ curl -s -H 'Accept-Language: sk' localhost:8000/products/ | grep -v '^$' <!DOCTYPE html> <html lang="sk"> <head> <meta charset="utf-8"> <title>Naše produkty</title> </head> <body> <h1>Naše produkty</h1> <p> Predávame 3 produkty. </p> <table> <tr><th>Názov</th><th>Cena</th><th>Pridaný</th></tr> <tr><td>Coffee mug</td><td>12,90</td><td>20. november 2026 14:30</td></tr> <tr><td>Desk lamp</td><td>1249,00</td><td>21. november 2026 8:05</td></tr> <tr><td>Notebook</td><td>4,50</td><td>21. november 2026 23:45</td></tr> </table> </body> </html>
Number and date formats
The formats come from the locale definitions shipped with Django, the files formats.py in django/conf/locale. Templates
localize the values automatically, and in Python code the module django.utils.formats does the same. The demo script formats a price,
a date, and a time in English, Slovak, and German; German is not offered by our site, but the formats work for any language that Django knows.
import os
from datetime import UTC, date, datetime
from decimal import Decimal
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.utils import formats, translation
price = Decimal('1249.5')
moment = datetime(2026, 11, 21, 8, 5, tzinfo=UTC)
for language in ['en', 'sk', 'de']:
with translation.override(language):
print(language,
formats.localize(price),
formats.number_format(price, 2, force_grouping=True),
formats.date_format(date(2026, 11, 21), 'SHORT_DATE_FORMAT'),
formats.date_format(moment, 'DATETIME_FORMAT'),
sep=' | ')
localize() changes only the decimal separator. The thousands separator is not used by default, because the setting
USE_THOUSAND_SEPARATOR is false; number_format() with force_grouping=True adds it: a comma in English,
a space in Slovak, and a dot in German. The names SHORT_DATE_FORMAT and DATETIME_FORMAT select formats of the active
language; the template filter date accepts the same names.
$ uv run python -m demos.formats en | 1249.5 | 1,249.50 | 11/21/2026 | Nov. 21, 2026, 8:05 a.m. sk | 1249,5 | 1 249,50 | 21.11.2026 | 21. november 2026 8:05 de | 1249,5 | 1.249,50 | 21.11.2026 | 21. November 2026 08:05
The language in the URL
Choosing the language from the header has a drawback: one URL returns different pages, which search engines and caches do not like, and the
visitor cannot change the language. The function i18n_patterns() puts the code of the language at the start of the paths that it
wraps, so that /sk/products/ is always Slovak. The URLs of django.conf.urls.i18n provide the view set_language,
which switches the language; it is not inside i18n_patterns(), because it must work in all languages.
from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns(
path('', include('catalog.urls')),
)
The template gets a form that posts the chosen language to set_language, with the current path in the field next.
The tag {% get_available_languages %} returns the pairs from LANGUAGES, whose lazy names appear in the active language.
The form needs the CSRF token, like every POST form in Django. This is the final version of the template.
{% load i18n %}
<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8">
<title>{% translate "Our products" %}</title>
</head>
<body>
<h1>{% translate "Our products" %}</h1>
<p>
{% blocktranslate count counter=products|length %}We sell {{ counter }} product.{% plural %}We sell {{ counter }} products.{% endblocktranslate %}
</p>
<table>
<tr>{% for field in fields %}<th>{{ field|capfirst }}</th>{% endfor %}</tr>
{% for product in products %}
<tr><td>{{ product.name }}</td><td>{{ product.price }}</td><td>{{ product.added }}</td></tr>
{% endfor %}
</table>
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.path }}">
{% get_available_languages as languages %}
<select name="language" aria-label="{% translate "Language" %}">
{% for code, name in languages %}
<option value="{{ code }}"{% if code == LANGUAGE_CODE %} selected{% endif %}>{{ name }}</option>
{% endfor %}
</select>
<button>{% translate "Switch" %}</button>
</form>
</body>
</html>
The two texts of the form are translated as before. With them the catalog is complete; this is the whole file as it is used by the rest of the article.
# Slovak translation of the shop. msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-11-21 16:13+0000\n" "PO-Revision-Date: 2026-11-21 10:00+0100\n" "Last-Translator: Jan Bodnar\n" "Language-Team: Slovak\n" "Language: sk\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n % 1 == 0 && n == 1 ? 0 : n % 1 == 0 && n " ">= 2 && n <= 4 ? 1 : n % 1 != 0 ? 2: 3);\n" #: catalog/models.py:6 msgid "name" msgstr "názov" #: catalog/models.py:7 msgid "price" msgstr "cena" #: catalog/models.py:8 msgid "added" msgstr "pridaný" #: catalog/models.py:11 msgid "product" msgstr "produkt" #: catalog/models.py:12 msgid "products" msgstr "produkty" #: catalog/templates/catalog/products.html:7 #: catalog/templates/catalog/products.html:10 msgid "Our products" msgstr "Naše produkty" #: catalog/templates/catalog/products.html:12 #, python-format msgid "We sell %(counter)s product." msgid_plural "We sell %(counter)s products." msgstr[0] "Predávame %(counter)s produkt." msgstr[1] "Predávame %(counter)s produkty." msgstr[2] "Predávame %(counter)s produktu." msgstr[3] "Predávame %(counter)s produktov." #: catalog/templates/catalog/products.html:24 msgid "Language" msgstr "Jazyk" #: catalog/templates/catalog/products.html:29 msgid "Switch" msgstr "Prepnúť" #: catalog/views.py:10 msgid "Welcome to our shop" msgstr "Vitajte v našom obchode" #: catalog/views.py:15 #, python-format msgid "There is %(count)d product in the cart." msgid_plural "There are %(count)d products in the cart." msgstr[0] "V košíku je %(count)d produkt." msgstr[1] "V košíku sú %(count)d produkty." msgstr[2] "V košíku je %(count)d produktu." msgstr[3] "V košíku je %(count)d produktov." #. Translators: the sign on the door says that the shop is open #: catalog/views.py:24 msgctxt "door sign" msgid "Open" msgstr "Otvorené" #. Translators: a button that opens the shopping cart #: catalog/views.py:26 msgctxt "button" msgid "Open" msgstr "Otvoriť" #: config/settings.py:112 msgid "English" msgstr "Angličtina" #: config/settings.py:113 msgid "Slovak" msgstr "Slovenčina"
After compilemessages the demo script uses a client that prefers Slovak, like a browser would. It requests the paths with and
without the prefix, switches to English with a POST request, and prints the status, the redirect target, and the language of the responses.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.test import Client
from django.test.utils import setup_test_environment
setup_test_environment()
def show(method, path, response):
where = response.get('Location', '')
print(f'{method:4} {path:16} {response.status_code} {where:16} {response.get("Content-Language", "")}')
client = Client(headers={'Accept-Language': 'sk,en;q=0.5'})
for path in ['/products/', '/sk/products/', '/en/products/', '/de/products/']:
show('GET', path, client.get(path))
response = client.post('/i18n/setlang/', {'language': 'en', 'next': '/sk/products/'})
show('POST', '/i18n/setlang/', response)
print('cookie:', response.cookies['django_language'].OutputString())
show('GET', '/products/', client.get('/products/'))
page = client.get('/sk/products/').content.decode()
print([line for line in page.splitlines() if 'option' in line or 'button' in line])
A path without a prefix is redirected to the language chosen from the header. The prefixed paths are served in their language whatever the
header says, and an unknown prefix gives 404 (the line Not Found is the log of the request). The view set_language
stores the choice in the cookie django_language and redirects to the next path translated to the new language, so
/sk/products/ became /en/products/. From then on the cookie wins over the header, and the redirect goes to the English
page. The last line shows the options of the switcher on the Slovak page.
$ uv run python -m demos.switch GET /products/ 302 /sk/products/ GET /sk/products/ 200 sk GET /en/products/ 200 en Not Found: /de/products/ GET /de/products/ 404 sk POST /i18n/setlang/ 302 /en/products/ sk cookie: django_language=en; Path=/ GET /products/ 302 /en/products/ ['<option value="en">Angličtina</option>', '<option value="sk" selected>Slovenčina</option>', '<button>Prepnúť</button>']
Time zones
With USE_TZ = True, which is the default, Django stores the times in UTC and works with aware datetime objects, which
carry their zone. The current time zone, by default TIME_ZONE, is used only to display the times and to interpret the
times entered in forms. Browsers do not send the zone of the user, so a site gets it from the user's profile or, as here, from a cookie that
JavaScript can set. The middleware activates a valid zone for the request and falls back to the default for a missing or invalid one.
import zoneinfo
from django.utils import timezone
class TimezoneMiddleware:
"""Activates the time zone from the cookie 'timezone', if it is valid."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
name = request.COOKIES.get('timezone', '')
try:
timezone.activate(zoneinfo.ZoneInfo(name))
except (ValueError, zoneinfo.ZoneInfoNotFoundError):
timezone.deactivate()
return self.get_response(request)
The middleware is added after LocaleMiddleware.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'catalog.middleware.TimezoneMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
The demo script reads the time of the lamp and shows it in four zones with timezone.override() and localtime().
The last lines filter the products by date; the lookup __date uses the current time zone as well.
import os
from datetime import UTC, datetime
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.utils import formats, timezone
from catalog.models import Product
lamp = Product.objects.get(name='Desk lamp')
print('stored :', lamp.added, lamp.added.tzinfo)
print('now :', timezone.now().tzinfo, timezone.is_aware(timezone.now()))
print('naive :', timezone.is_aware(datetime(2026, 11, 21, 8, 5)))
for name in ['UTC', 'Europe/Bratislava', 'America/New_York', 'Asia/Tokyo']:
with timezone.override(name):
local = timezone.localtime(lamp.added)
print(f'{name:18} {local.isoformat()} {formats.date_format(local, "DATETIME_FORMAT")}')
day = datetime(2026, 11, 21, tzinfo=UTC)
print('added on 21 Nov UTC:', Product.objects.filter(added__date=day.date()).count())
with timezone.override('Asia/Tokyo'):
print('added on 21 Nov in Tokyo:', Product.objects.filter(added__date=day.date()).count())
The stored value is in UTC, and timezone.now() is aware. Each zone shows the same moment with its own offset. The query results
differ: the notebook was added at 23:45 UTC on 21 November, which was already the 22nd in Tokyo, while the mug from the evening of the 20th still
counts for the 20th; so Tokyo has one product on the 21st, and UTC two.
$ uv run python -m demos.zones stored : 2026-11-21 08:05:00+00:00 UTC now : UTC True naive : False UTC 2026-11-21T08:05:00+00:00 Nov. 21, 2026, 8:05 a.m. Europe/Bratislava 2026-11-21T09:05:00+01:00 Nov. 21, 2026, 9:05 a.m. America/New_York 2026-11-21T03:05:00-05:00 Nov. 21, 2026, 3:05 a.m. Asia/Tokyo 2026-11-21T17:05:00+09:00 Nov. 21, 2026, 5:05 p.m. added on 21 Nov UTC: 2 added on 21 Nov in Tokyo: 1
With the server running, a request with the cookie shows the times of the list in the zone of Tokyo; an invalid name falls back to UTC.
$ curl -s -b timezone=Asia/Tokyo localhost:8000/en/products/ | grep '<td>' <tr><td>Coffee mug</td><td>12.90</td><td>Nov. 20, 2026, 11:30 p.m.</td></tr> <tr><td>Desk lamp</td><td>1249.00</td><td>Nov. 21, 2026, 5:05 p.m.</td></tr> <tr><td>Notebook</td><td>4.50</td><td>Nov. 22, 2026, 8:45 a.m.</td></tr> $ curl -s -b timezone=Mars/Olympus localhost:8000/en/products/ | grep '<td>' <tr><td>Coffee mug</td><td>12.90</td><td>Nov. 20, 2026, 2:30 p.m.</td></tr> <tr><td>Desk lamp</td><td>1249.00</td><td>Nov. 21, 2026, 8:05 a.m.</td></tr> <tr><td>Notebook</td><td>4.50</td><td>Nov. 21, 2026, 11:45 p.m.</td></tr>
Testing translations
Tests request the prefixed URLs or send Accept-Language headers; for code outside of requests, translation.override()
activates a language for a block. The tests check the Slovak page, the redirects, the plural forms of the catalog, and the time zone cookie.
The test client keeps cookies in self.client.cookies.
from datetime import UTC, datetime
from django.test import TestCase
from django.utils import translation
from django.utils.translation import ngettext
from .models import Product
class TranslationTests(TestCase):
@classmethod
def setUpTestData(cls):
Product.objects.create(name='Coffee mug', price='12.90',
added=datetime(2026, 11, 20, 14, 30, tzinfo=UTC))
def test_slovak_page(self):
response = self.client.get('/sk/products/')
self.assertContains(response, '<h1>Naše produkty</h1>', html=True)
self.assertContains(response, '12,90')
self.assertEqual(response['Content-Language'], 'sk')
def test_redirect_by_accept_language(self):
response = self.client.get('/products/', headers={'Accept-Language': 'sk'})
self.assertRedirects(response, '/sk/products/')
def test_unknown_language_falls_back_to_english(self):
response = self.client.get('/products/', headers={'Accept-Language': 'fr'})
self.assertRedirects(response, '/en/products/')
def test_slovak_plural_forms(self):
text = 'There is %(count)d product in the cart.'
plural = 'There are %(count)d products in the cart.'
with translation.override('sk'):
forms = [ngettext(text, plural, n) % {'count': n} for n in (1, 3, 7)]
self.assertEqual(forms, ['V košíku je 1 produkt.', 'V košíku sú 3 produkty.',
'V košíku je 7 produktov.'])
def test_time_zone_cookie(self):
self.client.cookies['timezone'] = 'Asia/Tokyo'
response = self.client.get('/en/products/')
self.assertContains(response, 'Nov. 20, 2026, 11:30 p.m.')
The tests use the compiled catalog, so compilemessages must have been run before. All five tests pass.
$ uv run python manage.py test catalog 2>&1 Found 5 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). ..... ---------------------------------------------------------------------- Ran 5 tests in 0.015s OK Destroying test database for alias 'default'...
Source
Django documentation: Translation
Django documentation: Format localization
Django documentation: Time zones
GNU gettext manual: The format of PO files
In this article we have translated a Django application: we marked texts with gettext(), ngettext(), and
pgettext(), created and compiled the catalog with makemessages and compilemessages, used lazy translation
in models, translated templates, formatted numbers and dates, put the language into the URL with a switcher, displayed times in the zone of the
visitor, and tested the result. Related articles are Django templates,
Django middleware, and Django settings and environment.
Author
List all Django tutorials.