Languages and translations
Use Django gettext for source-code strings, the Chassis translation catalog
for operator-managed interface text, and TranslateField for localized
business records. All three can use the current account's language.
Enable language preferences
Install and migrate django_chassis, with the app listed before
django.contrib.admin. The Chassis AdminSite registers Languages and
Translation keys, including when the users module is disabled. Import
LOCALIZATION_SIDEBAR_SECTION from django_chassis.sidebar and add it to the
site's sidebar_items to link to both models. With AdminSite
at /admin/, the preference form submits to /admin/language/
(<site-name>:chassis_language_preference). Set USE_I18N = True for gettext
and place the profile middleware after authentication and any Django
LocaleMiddleware. Keep the rest of the existing middleware list.
# In the project's existing MIDDLEWARE list, keep this relative order.
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_chassis.middlewares.ProfileLanguageMiddleware',
]
The same account preference applies across hosts that use the same profile database. An anonymous user, a missing profile, or a profile whose preference is inactive uses the primary language. Disabling a language preserves saved preferences. Reactivation makes them effective again.
| Admin task | Model permissions |
|---|---|
| Open Languages, change names or activation, add a language | django_chassis.view_language, django_chassis.change_language, django_chassis.add_language as needed |
| Open Translation keys, create, edit or delete a translation | django_chassis.view_translationkey, django_chassis.add_translationkey, django_chassis.change_translationkey, django_chassis.delete_translationkey as needed |
| Change your own language in Admin | Active staff access and an active destination language |
Russian starts active and primary. English starts inactive. To add French, select an unused ISO 639 alpha-2 code, enter a name and choose an existing language as the catalog source. The copy starts inactive. Prepare translations before activating it. The last active language stays available. If you have more than two active languages, choose a different primary before deactivating the current one.
Manage a translation catalog
Open Translation keys and select a language tab. The primary language comes first. Inactive languages remain editable. Enter the exact key when adding a translation on another tab. Editing preserves the key and the other languages. Deleting a translation removes only its language row.
Each language, key, and translation records its own creation time in created_at.
Editing or reimporting an existing record preserves its creation time.
A language's updated_at is empty at creation and records later name,
availability, or primary-language changes.
This example can run in python manage.py shell after migration.
from django_chassis.services import LanguageService, TranslationService
languages = LanguageService()
languages.set_active(code='en', active=True)
texts = TranslationService()
texts.merge(language='ru', entries={
'catalog.title': 'Каталог',
'catalog.progress': 'Готово: %d%%'
})
texts.merge(language='en', entries={
'catalog.title': 'Catalog',
'catalog.progress': 'Progress: %d%%'
})
assert texts.get('catalog.progress', language='en', args=(80,)) == 'Progress: 80%'
assert texts.get_many(['catalog.title', 'missing.key'], language='en') == {
'catalog.title': 'Catalog',
'missing.key': ''
}
A JSON import or merge(language=..., entries=...) accepts a flat dictionary
of nonempty keys and string values. A new key seeds every configured language
with the imported text. Importing an existing key updates only the selected
language. Omitted keys are preserved. Export with
TranslationService.export(language='en') or via the
translation catalog transfer. An
unknown language or invalid input raises ValidationError. Inactive languages
can be prepared by import.
get() and get_many() read an explicit language first if supplied.
Otherwise they use the profile preference if active. Missing or empty text
falls back to the primary language and finally to an empty string. Pass
args=(...) to get() to apply positional Python percent formatting after
fallback. Store the same placeholders in all translations. Invalid arguments
raise Python's formatting error.
Catalog transfer permissions
To use transfer in Admin, also grant the operation permissions with the
django_chassis prefix. Import uses view_translation_import and
upload_translation_import. Export uses view_translation_export,
create_translation_export and download_translation_export.
Add a translated model field
from django.db import models
from django_chassis.services import TranslationService
from django_chassis.fields import TranslateField
class Product(models.Model):
description = TranslateField(default=dict, blank=True)
def description_for(self, language: str) -> str:
return TranslationService.read_field(self.description, language=language)
In 1.0.23, keep the imports in the order shown. Importing TranslateField
first in a fresh process can trigger a circular import.
Generate and apply the product app's migration, then register the model on
your Chassis AdminSite. The model stores a JSON object such as
{"ru": "Роза", "en": "Rose"}. The generated form shows a textarea per active
language. A save replaces those translations and preserves inactive ones. If
activation changes while a form is open, reload to get the current fields.
When blank=False, supply text in at least one active language.
To display the value in a project view or API, pass its dictionary to
TranslationService.read_field(product.description, language=request.LANGUAGE_CODE)
when the middleware is installed, or supply profile=profile. Store only
configured language codes and string values on model writes.