lr_optim
lr_optim

Reputation: 381

Can I manually feed the language code to Django gettext()?

I have a few strings in the backend I'd need to occasionally translate to other language before using them. I plan to save the user language selection into the database so it would be easy to get it from there. But, what is unclear for me, is if I implement localization and have a couple of different language files, how can I use the right language version? I can't read the language selection from cookies, url, user session etc. Can I use the language code from my database to choose which translation I'll use?

Upvotes: 1

Views: 1116

Answers (1)

Marco
Marco

Reputation: 2834

You can manually activate the language with activate. Here's an example, given the user has an language attribute with a valid language code:

from django.utils.translation import activate, deactivate
from django.utils.translation import gettext as _

user = MyUserModel.objects.get(username=username)
activate(user.language)
my_string_translated_into_users_language = _("Hello")
deactivate()

That way, you override the current session language. Then deactivate() will deactivate the currently active translation object so that further _ calls will resolve against the default translation object, again.

Upvotes: 3

Related Questions