Guy*_*den 49 django internationalization
背景: 当支付服务在幕后追回付款结果时调用该视图 - 之后我需要以正确的语言发送电子邮件以确认付款等等.我可以在支付服务器的请求中获取语言代码,并希望将其与Django的i18n系统一起使用,以确定将我的电子邮件发送到哪种语言.
所以我需要在视图中设置我的django应用程序的语言.然后一次性完成我的模板渲染和电子邮件.
设置request.session['django_language'] = lang
仅在我测试时影响下一个视图.
还有其他办法吗?
干杯,
家伙
ste*_*anw 79
引用Django的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()
Run Code Online (Sandbox Code Playgroud)
这translation.activate(language)
是重要的一点.
web*_*kie 12
一定要在process_response中添加deactivate,否则你会遇到不同线程的问题.
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
Run Code Online (Sandbox Code Playgroud)
如果只是想出于某种原因获取某种语言的翻译字符串,您可以使用override
如下装饰器:
from django.utils import translation
from django.utils.translation import ugettext as _
with translation.override(language):
welcome = _('welcome')
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以考虑将语言存储在用户模型中并使用此自定义中间件django-user-language-middleware。
这样您就可以通过查看字段中所选的语言来轻松翻译您的 Django 应用程序user.language
,并且您始终可以了解任何用户的语言偏好。
用法:
将语言字段添加到您的用户模型中:
class User(auth_base.AbstractBaseUser, auth.PermissionsMixin):
# ...
language = models.CharField(max_length=10,
choices=settings.LANGUAGES,
default=settings.LANGUAGE_CODE)
Run Code Online (Sandbox Code Playgroud)从 pip 安装中间件:
pip install django-user-language-middleware
将其添加到设置中的中间件类列表中以监听请求:
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'user_language_middleware.UserLanguageMiddleware',
...
]
Run Code Online (Sandbox Code Playgroud)我希望这可以帮助人们将来解决这个问题。
归档时间: |
|
查看次数: |
39898 次 |
最近记录: |