Django: line feed without using session / cookie language

Is there a way in django to translate a string into a different language than the one specified in the session or language cookie?

I mean doing this when calling ugettext. Something like this, where 'en' is the language code:

from django.utils.translation import ugettext as _

def translate():
   translated_string =  _('Translate me', 'en')
+3
source share
1 answer

Looking through django/middleware/locale.py, it seems you can just call:

from django.utils import translation
translation.activate(language)

Here's the whole class LocaleMiddleware, for your guidance:

def process_request(self, request):
    language = translation.get_language_from_request(request)
    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()

def process_response(self, request, response):
    patch_vary_headers(response, ('Accept-Language',))
    if 'Content-Language' not in response:
        response['Content-Language'] = translation.get_language()
    translation.deactivate()
    return response
+5
source

Source: https://habr.com/ru/post/1719957/


All Articles