#10122: setting locales for a single HTTP context ------------------------------------------------------------------------+--- Reporter: mathijs | Owner: nobody Status: new | Milestone: Component: Documentation | Version: 1.0 Keywords: internationalisation, context, rendering, template, locale | Stage: Unreviewed Has_patch: 0 | ------------------------------------------------------------------------+--- 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 -- Ticket URL: <http://code.djangoproject.com/ticket/10122> Django <http://code.djangoproject.com/> The Web framework for perfectionists with deadlines. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django updates" group. To post to this group, send email to django-updates@googlegroups.com To unsubscribe from this group, send email to django-updates+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-updates?hl=en -~----------~----~----~----~------~----~------~--~---