Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 703
Guy Bowden Avatar asked Feb 25 '10 19:02

Guy Bowden


People also ask

How does Django implement multi language?

You have to add {% load i18n %} at the top of the HTML file to use the translation templates tags. The {% trans %} template tag allows you to mark a literal for translation. Django simply executes the gettext function on the given text internally.

What is lazy text in Django?

Use the lazy versions of translation functions in django. utils. translation (easily recognizable by the lazy suffix in their names) to translate strings lazily – when the value is accessed rather than when they're called. These functions store a lazy reference to the string – not the actual translation.

What is USE_I18N in Django?

Django's internationalization hooks are on by default, and that means there's a bit of i18n-related overhead in certain places of the framework. If you don't use internationalization, you should take the two seconds to set USE_I18N = False in your settings file.


1 Answers

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.

like image 84
stefanw Avatar answered Oct 21 '22 13:10

stefanw