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, 'customer@example.org', ['admin@example.org'])
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.
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.
Not sure if activating/deactivating translation is proper way to solve that problem(?)
If I were facing that problem I would try to build some model for storing subjects/body/language/type fields. Some code draft:
class ClientMessageTemplate(models.Model):
language = model.CharField(choices=AVAIALBLE_LANGUAGES,...)
subject = models.CharField(...)
body = models.CharField(...)
type = models.CharField(choices=AVAILABLE_MESSAGE_TYPES)
Then you can retreive easily ClientMessageTemplate you need base on type and client's language.
Advantage of this solution is that you can have all data maintainable via admin interface and do not need to recompile message files each time something changed.
精彩评论