Django:i18n - 更改语言

发布于 2024-10-27 12:56:16 字数 1682 浏览 1 评论 0 原文

我安装了 model_translation、rosetta、locale_url。但改变语言不起作用。

我的settings.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/语言开关,但是当切换到另一个页面时-语言又恢复为默认语言。 我应该怎么办?

I installed model_translation, rosetta, locale_url. But does not work change language.

My settings.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')),
)

My view for a language switch:

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

In templates:

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

My middleware:

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',
)

But the language switching does not work. If I turn on the link http://localhost/uk/ language switch, but when switching to another page - the language back to the default language.
What should I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

世界等同你 2024-11-03 12:56:16

将 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

add translation.activate to your code:

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
忆沫 2024-11-03 12:56:16

我遇到了同样的问题,这是因为 next 参数前面加上了旧的语言代码,这会阻止新的语言代码生效。 (感谢@Pedro 的回答提供了线索)。

要解决此问题,如果您在模板中使用 {{ request.path }}{{ request.get_full_path }} (或根本不设置它)重定向到相同的翻译,然后您必须指定下一个,按如下方式切片语言代码。其余部分保留为 文档说

<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />

我发布了一个答案,更详细地解释了这一点,并提供了两个功能示例。

I faced the same problem and it was because the next parameter is prepended with the old language code and this prevents the new one to take effect. (Thanks to @Pedro's answer for giving a clue on this).

To solve this, if you're using {{ request.path }} or {{ request.get_full_path }} from your template (or not setting it at all) to redirect to the same translated one, then you have to specify the next, slicing the language code as follows. The rest stays as the the docs say:

<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />

I posted an answer explaining this in more detail and providing two functional examples.

献世佛 2024-11-03 12:56:16

使用 Torsten 发布的代码,您的 URL 不会更改,因为“下一个”将始终类似于 */ru/*other/urls。它永远不会是None(实际上上面的两个if都没用)。您的语言会因 set_cookietranslation.activate 而发生变化。但是,当您单击网站中的任何其他英语链接时,语言将恢复为 ru。

您可以尝试 django 的 set_language 内置视图,如解释的这里,或者通过尝试一些替换或类似的操作来处理“下一个”字符串。

Using the code posted by Torsten, your URL won't change because 'next' will always be something like */ru/*other/urls. It will never be None (actually the two if's above are useless). Your language changes because of the set_cookie and translation.activate. But when you click any other link in your site in English, the language will go back to ru.

You can try the set_language builtin view from django, like explained here, or process the 'next' string by trying some replace or something like that.

碍人泪离人颜 2024-11-03 12:56:16

你可以试试这个。此代码将与 get 请求一起使用

def set_language(request):
    from django.utils.translation import activate
    lang_code = request.GET.get('language', 'en')
    lang = get_language()
    if not lang_code:
        lang_code = request.GET.get('lang_code', settings.LANGUAGE_CODE)
    next_url = request.META.get('HTTP_REFERER', '')
    if not is_safe_url(url=next_url, host=request.get_host()):
        next_url = '/'
    response = HttpResponseRedirect(next_url)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
        activate(lang_code)
    return response

,或者您可以使用内置设置语言选项。这适用于 POST 请求
https://docs.djangoproject.com /en/dev/topics/i18n/translation/#django.views.i18n.set_language

You can try this . this code will work with get request

def set_language(request):
    from django.utils.translation import activate
    lang_code = request.GET.get('language', 'en')
    lang = get_language()
    if not lang_code:
        lang_code = request.GET.get('lang_code', settings.LANGUAGE_CODE)
    next_url = request.META.get('HTTP_REFERER', '')
    if not is_safe_url(url=next_url, host=request.get_host()):
        next_url = '/'
    response = HttpResponseRedirect(next_url)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
        activate(lang_code)
    return response

or you can use built set language option . this will work with POST request
https://docs.djangoproject.com/en/dev/topics/i18n/translation/#django.views.i18n.set_language

淡写薰衣草的香 2024-11-03 12:56:16

您可以按照i18n切换器 rel="nofollow noreferrer">set_language 重定向视图,因此您无需自己创建它。您可以查看我的回答我的回答解释了如何创建i18n 切换器 分别用于 Django 和 Django Admin。

You can easily create i18n switcher following The set_language redirect view so you don't need to create it by yourself. You can see my answer and my answer explaining how to create i18n switcher for Django and Django Admin respectively.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文