Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: switch language of message sent from admin panel

I have a model, Order, that has an action in the admin panel that lets an admin send information about the order to certain persons listed that order. Each person has language set and that is the language the message is supposed to be sent in.

A short version of what I'm using:

from django.utils.translation import ugettext as _
from django.core.mail import EmailMessage

lang = method_that_gets_customer_language()

body = _("Dear mister X, here is the information you requested\n")
body += some_order_information

subject = _("Order information")

email = EmailMessage(subject, body, '[email protected]', ['[email protected]'])
email.send()

The customer information about the language he uses is available in lang. The default language is en-us, the translations are in french (fr) and german (de).

Is there a way to use the translation for the language specified in lang for body and subject then switch back to en-us? For example: lang is 'de'. The subject and body should get the strings specified in the 'de' translation files.

edit:

Found a solution.

from django.utils import translation
from django.utils.translation import ugettext as _


body = "Some text in English"
translation.activate('de')
print "%s" % _(body)
translation.activate('en')

What this does it take the body variable, translates it to German, prints it then returns the language to English.

Something like

body = _("Some text in English")
translation.activate('de')
print "%s" % body

prints the text in English though.

like image 201
Virgiliu Avatar asked Apr 17 '10 13:04

Virgiliu


1 Answers

If you're using Python 2.6 (or Python 2.5 after importing with_statement from __future__) you can use the following context manager for convenience.

from contextlib import contextmanager
from django.utils import translation

@contextmanager
def language(lang):
    if lang and translation.check_for_language(lang):
        old_lang = translation.get_language()
        translation.activate(lang)

    try:
        yield
    finally:
        if lang:
            translation.activate(old_lang)

Example of usage:

message = _('English text')
with language('fr'):
    print unicode(message)

This has the benefit of being safe in case something throws an exception, as well as restoring the thread's old language instead of the Django default.

like image 100
sciyoshi Avatar answered Oct 10 '22 19:10

sciyoshi