Internalization

django-modern-rest supports optional i18n feature which is provided by the Django itself.

Docs: https://docs.djangoproject.com/en/stable/topics/i18n/

Note

If no configuration is specified, we default to en-us locale. If you just want to use the default language, you don’t have to do anything.

Core features:

Enabling translated API messages

Note

See full list of the supported languages here.

Setting the default language code for all users:

settings.py
LANGUAGE_CODE = 'ru-ru'

Setting the language code per request:

settings.py
MIDDLEWARE = [
    # ...
    'django.middleware.locale.LocaleMiddleware',
]

Then any requests with Accept-Language header will set the required language for this specific response.

Run result

$ curl http://127.0.0.1:8000/api/lang/ -X POST -H 'Accept-Language: ru'
{"detail":[{"msg":"Не аутентифицирован","type":"security"}]}

Specifying the list of the supported languages:

settings.py
from django.utils.translation import gettext_lazy as _

LANGUAGES = [
    ('ru', _('Russian')),
    ('en', _('English')),
]

Important

Whenever you use Django’s built-in translation feature, don’t forget to run compilemessages management command before using the translations.

Enabling translation for type validation

Since we are using pydantic and msgspec directly to handle all type validation and schema checks, their messages won’t be affected by the Django’s i18n settings.

If you want to translate their messages as well, use their own docs:

You can customize dmr.serializer.BaseSerializer.serialize_validation_error() on the serializer that needs the validation errors to be translated. Or you can change dmr.controller.Controller.format_error() method to translate messages there.

Forcing constant API language

If you have a website using some non-English LANGUAGE_CODE and you want to add an API that will always use

And then add it to your MIDDLEWARE setting:

settings.py
MIDDLEWARE = [
    # ...
    'path.to.ForceEnglishForAPI',
    # ...
]

Adding local translations

If you are using a language that is not supported by django-modern-rest natively, you can translate them right in your own local project.

Here’s how to do it:

  1. Create a directory called locale/ inside your project and add it to LOCALE_PATHS setting in settings.py

  2. Create a language directory inside locale/, for example: locale/pt-br/, with the locale name that you want to support. See ISO 639 for the list of the language codes

  3. Take the initial translation template from our repository

  4. Fill in the translations

  5. Run python manage.py compilemessages -l pt-br, where pt-br is the locale you want to support

  6. Restart your development server with python manage.py runserver, if you want to see the changes

Please, contribute your translation back to django-modern-rest! It would be a good addition to the library.