gpt4 book ai didi

Django: i18n - 更改语言

转载 作者:行者123 更新时间:2023-12-04 00:44:21 29 4
gpt4 key购买 nike

我正在安装 model_translation、rosetta、locale_url。但不工作改变语言。

我的设置.py:

LANGUAGE_CODE = 'ru'
MODELTRANSLATION_TRANSLATION_REGISTRY = "project.translation"
TRANSLATION_REGISTRY = "project.translation"
ugettext = lambda s: s
LANGUAGES = (
('ru', ugettext(u'Russian')),
('uk', ugettext(u'Ukrainian')),
)

我对语言切换的看法:
def set_language(request):
next = request.REQUEST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'GET':
lang_code = request.GET.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
return response

在模板中:
<a href="{% url set_lang %}?lang=uk&next={{request.path}}">Ukranian</a>

我的中间件:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'localeurl.middleware.LocaleURLMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

但是语言切换不起作用。如果我打开链接 http://localhost/uk/语言切换,但是当切换到另一个页面时 - 语言回到默认语言。
我该怎么办?

最佳答案

将 translation.activate 添加到您的代码中:

from django.utils import translation

def set_language(request):
next = request.REQUEST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'GET':
lang_code = request.GET.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
translation.activate(lang_code)
return response

关于Django: i18n - 更改语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489601/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com