Search code examples
pythondjangodjango-viewsdjango-i18n

load language file temporarily for specific purpose only


I am using gettext(), which works very fine depending on the logged in user's preference. Currently, there are French and English languages. THe app is django 1.11 with python 3.4

Now, an English is loaded for user A. But he wants to send a predefined message to User B, who has indicated French as his preferred language. Without reloading the loaded language, is there a simple way to load the french language for that specific task, get the required message by its msgid and destroy it from memory?

The current solution in the existing system is to read Json files for such tasks. But I am looking forward to have one language file for each language (.po) instead of Json and po files.


Solution

  • If your task is in a view, you can change the language temporarily with this code:

    translation.activate(lang)
    

    and don't forget to import "translation":

    from django.utils import translation
    

    an example:

    user_A_lang = translations.get_language()
    user_B_lang = "en"
    # activate the new language
    translation.activate(user_B_lang)
    # the way you use to translate
    my_translated_string = _("String to be translated")
    # activate the original language
    translation.activate(user_A_lang)