How to translate a Django project into a different language

  • 2 months ago
This videos shows an easy way to translate a Django project into a different language.

You just need to follow several steps, use gettext to translate a string
from django.utils.translation import gettext as _

def index(request):
return HttpResponse(_("Hello, world!"))

Create a middleware for the languge
class LanguageMiddleware:
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
self.get_response = get_response
self.default_language: str = getattr(settings, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)

def __call__(self, request):
activate(self.default_language)
return self.get_response(request)

Enable the middleware support and add the language middleware into the settings.py file
MIDDLEWARE = [
'django.middleware.locale.LocaleMiddleware',
'api.middleware.LanguageMiddleware'
]

In the settings.py specify where will be located the languages files
LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]

Run CLI command to extract the strings and save in the wanted directory
python manage.py makemessages -l

Run the CLI command to compile the PO files into MO
python manage.py compilemessages

In the following videos will be one where I will show another way to integrate multiple languages with pssibility to save the language in the user settings and translate both Django backend and Angular frontend.

If you like my videos, please, Subscribe. Thank you.

Recommended