Surprise Me!

How to translate a Django project into a different language

2024-06-02 4 Dailymotion

This videos shows an easy way to translate a Django project into a different language.<br /><br />You just need to follow several steps, use gettext to translate a string<br />from django.utils.translation import gettext as _<br /><br />def index(request):<br /> return HttpResponse(_("Hello, world!"))<br /><br />Create a middleware for the languge<br />class LanguageMiddleware:<br /> def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:<br /> self.get_response = get_response<br /> self.default_language: str = getattr(settings, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)<br /><br /> def __call__(self, request):<br /> activate(self.default_language)<br /> return self.get_response(request)<br /><br />Enable the middleware support and add the language middleware into the settings.py file<br />MIDDLEWARE = [<br /> 'django.middleware.locale.LocaleMiddleware',<br /> 'api.middleware.LanguageMiddleware'<br />]<br /><br />In the settings.py specify where will be located the languages files<br />LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]<br /><br />Run CLI command to extract the strings and save in the wanted directory<br />python manage.py makemessages -l<br /><br />Run the CLI command to compile the PO files into MO<br />python manage.py compilemessages<br /><br />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.<br /><br />If you like my videos, please, Subscribe. Thank you.

Buy Now on CodeCanyon