vishes_shell
vishes_shell

Reputation: 23484

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?

Upvotes: 0

Views: 3319

Answers (2)

Mina Roger
Mina Roger

Reputation: 109

Maybe It's too late but you can add middleware in Settings file

MIDDLEWARE + = [ 'django.middleware.locale.LocaleMiddleware',]

And in request header Key =Accept-Language Value= en, So now Django will switch the language base on the request header.

Upvotes: 2

vishes_shell
vishes_shell

Reputation: 23484

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)

Upvotes: 2

Related Questions