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

查看:27
本文介绍了在 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.

还有其他方法吗?

干杯,

男人

推荐答案

引用 Django 的 Locale Middleware (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天全站免登陆