Suggestion: Context manager for translation.activate

36 views
Skip to first unread message

Raphael Michel

unread,
Sep 20, 2016, 8:11:32 AM9/20/16
to django-d...@googlegroups.com
Hi,

in my application, I regularly need to switch the active language for a
short period of time. A popular example would be that a German-speaking
user does something and I need to send out a notification to an
English-speaking user.

Cluttering the code with translation.activate() statements is certainly
not making the core more readable, which is why I'm now using a context
manager:

with language(other_user.locale):
send_mail()

language() is currently implemented in my project like this:

@contextmanager
def language(lng):
_lng = translation.get_language()
translation.activate(lng or settings.LANGUAGE_CODE)
try:
yield
finally:
translation.activate(_lng)

This turned out to be very convenient and readable and I'd wanted to ask
for your opinion if

(a) something like this should be added to django
(b) the activate() method itself should be changed to optionally work as
a context manager

Cheers
Raphael

Raphael Michel

unread,
Sep 20, 2016, 8:12:45 AM9/20/16
to django-d...@googlegroups.com
Could you just ignore that I've ever sent this mail? Apparently, I
wasn't able to finde translation.override in the docs.

Sorry for the noise.
Raphael

Am Tue, 20 Sep 2016 14:11:11 +0200
schrieb Raphael Michel <ma...@raphaelmichel.de>:
Reply all
Reply to author
Forward
0 new messages