djangointernationalization

set language within a django view


background: The view is called when a payment service pings back a payment outcome behind the scenes - afterwhich I need to send an email in the right language to confirm payment and so on. I can get the language code back in the request from the payment server and would like to use that along with Django's i18n systems to determine which language to send my email out in.

So I need to set the language of my django app from within a view. And then do my template rendering and emailing all in one go.

setting request.session['django_language'] = lang only effects the next view when I'm testing.

Is there any other way to do it?

Cheers,

Guy


Solution

  • To quote parts from Django's Locale Middleware (django.middleware.locale.LocaleMiddleware):

    from django.utils import translation
    
    class LocaleMiddleware(object):
        """
        This is a very simple middleware that parses a request
        and decides what translation object to install in the current
        thread context. This allows pages to be dynamically
        translated to the language the user desires (if the language
        is available, of course).
        """
    
        def process_request(self, request):
            language = translation.get_language_from_request(request)
            translation.activate(language)
            request.LANGUAGE_CODE = translation.get_language()
    

    The translation.activate(language) is the important bit.