Search code examples
pythondjangodjango-i18ndjango-modeltranslation

How to change language in django-modeltranslation in function


I am using django-modeltranslation for translation some fields in my models. The package works great, everything is translated.

But there is no easy method to switch language manually.

From reading Accessing Translated and Translation Fields:

Because the whole point of using the modeltranslation app is translating dynamic content, the fields marked for translation are somehow special when it comes to accessing them. The value returned by a translated field is depending on the current language setting. “Language setting” is referring to the Django set_language view and the corresponding get_lang function.

Using set_language() as it described in documentation doesn't work. Got:

AttributeError: 'str' object has no attribute 'POST'

This is probably happening because i run set_language() not in view.

The question: How i can switch language for django-modeltranslation in basic function?


Solution

  • There is a method called activate() from django.utils.translation which is super simple:

    >>> from django.utils.translation import activate
    >>> activate('en')
    >>> Model.objects.first()  # will fetch english version
    >>> activate('fr')
    >>> Model.objects.first()  # will fetch french version
    

    This will work in views as well as plain functions.

    If you want to change language just for one fetch and return back to current language you can use get_language from django.utils.translation:

    >>> from django.utils.translation import get_language, activate
    >>> current_language = get_language()
    >>> activate('fr')
    >>> Model.object.first()
    >>> activate(current_language)