Currently there's no good explenation on how to set the locale temporarily, eg. when rendering one template in a different language used in emails.
I recently needed this as my users trigger email notifications for other users. These should be translated into the recieving users' languages. The code I used was:
from django.utils.translation import check_for_language, activate, deactivate, to_locale, get_language, ugettext as _
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.template import RequestContext
from django.contrib.sessions.middleware import SessionMiddleware
# 1. Get the current language: (if any)
cur_locale = to_locale(get_language())
# 2. create a request (& optionally add session middleware)
request = HttpRequest()
SessionMiddleware().process_request(request)
# 3. activate the users language: this loads the translation files
if check_for_language(target.user.language):
activate(target.user.language)
locale = to_locale(get_language())
# 4. set the language code in the request (& optionally session)
request.LANGUAGE_CODE = locale
request.session['django_language'] = locale
# 5. translate any string here (passed into the template):
msg_dict = { 'title': _('This is the title and will be translated'), 'body': _('Message body') }
# 6. render template with correct language:
rendered = render_to_string("some_template.html", msg_dict, RequestContext(request));
# 7. reset back to the old locale:
deactivate()
I don't know if there is any easier way to do this, if so let me know ;) if not, this could be included in the docs
I forgot to mention that target.user is my UserProfile class and the language property is thus the language preference for that user.