简体   繁体   English

Django-强制会话的默认语言,与MODELTRANSLATION_DEFAULT_LANGUAGE不同

[英]Django - force default language for sessions, different from MODELTRANSLATION_DEFAULT_LANGUAGE

I use Django with Mezzanine. 我将Django与Mezzanine结合使用。 I set languages like that: 我设置这样的语言:

LANGUAGE_CODE = "en"

MODELTRANSLATION_DEFAULT_LANGUAGE = 'cs'

LANGUAGES = (
    ('cs', _('Čeština')),
    ('en', _('Angličtina')),
)

I do NOT use language in URLs. 我不在网址中使用语言。

The problem is, that default language for new session is selected according browser preferences, however it should be EN allways. 问题在于,将根据浏览器首选项选择用于新会话的默认语言,但是始终应为EN。

How to achieve that? 如何实现呢?

I can imagine that it is possible to replace https://docs.djangoproject.com/en/2.1/_modules/django/middleware/locale/ with my custom middleware. 我可以想象有可能用我的自定义中间件替换https://docs.djangoproject.com/en/2.1/_modules/django/middleware/locale/ I guess I should change the function: 我想我应该更改功能:

def process_request(self, request):
    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
    language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
    language_from_path = translation.get_language_from_path(request.path_info)
    if not language_from_path and i18n_patterns_used and not prefixed_default_language:
        language = settings.LANGUAGE_CODE
    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()

Is there a simpler option? 有没有更简单的选择?

What I should change in the mentioned function to achieve desired behavior? 我应该在上述功能中进行哪些更改以实现所需的行为?

At the end I figure out that the simplest way is to add my custom middleware: 最后,我发现最简单的方法是添加我的自定义中间件:

from django.conf import settings
from django.utils import translation

class ForceLangMiddleware:

    def process_request(self, request):
        request.META['HTTP_ACCEPT_LANGUAGE'] = "en"

This middleware needs to be loaded before the other middlewares. 需要先加载该中间件,然后再加载其他中间件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM