set language within a django view

后端 未结 8 2115
暖寄归人
暖寄归人 2020-11-30 20:45

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 langu

8条回答
  •  生来不讨喜
    2020-11-30 21:20

    Be sure to also add deactivate in process_response, otherwise you will have problems with different threads.

    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()
    
        def process_response(self, request, response):
            translation.deactivate()
            return response
    

提交回复
热议问题