Django: switch language of message sent from admin panel Django: switch language of message sent from admin panel django django

Django: switch language of message sent from admin panel


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 contextmanagerfrom django.utils import translation@contextmanagerdef 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.