在django视图中设置语言 [英] set language within a django view

查看:139
本文介绍了在django视图中设置语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:
当支付服务在幕后回拨付款结果时,调用视图 - 之后,我需要使用正确的语言发送电子邮件以确认付款等。我可以从付款服务器的请求中获取语言代码,并希望与Django的i18n系统一起使用,以确定哪种语言可以发送我的电子邮件。

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.

所以我需要从视图中设置我的django应用程序的语言。然后再一次完成我的模板渲染和电子邮件。

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.

设置 request.session ['django_language'] = lang 仅在测试时影响下一个视图。

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

还有其他方法吗?

cheers,

Guy

推荐答案

从Django的区域中间件( django.middleware.locale.LocaleMiddleware ):

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()

translation.activate(language)是重要的一点。

这篇关于在django视图中设置语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆