检测语言& django locale-url

时间:2009-10-06 20:40:02

标签: django localization django-middleware

我想用英语和英语部署一个网站西班牙语并检测用户浏览器语言&重定向到正确的区域设置站点。

我的网站是www.elmalabarista.com

我安装了django-localeurl,但我发现没有正确检测到该语言。

这是我的中间件:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.locale.LocaleMiddleware',    
    'multilingual.middleware.DefaultLanguageMiddleware',
    'middleware.feedburner.FeedburnerMiddleware',
    'lib.threadlocals.ThreadLocalsMiddleware',
    'middleware.url.UrlMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'maintenancemode.middleware.MaintenanceModeMiddleware',
    'middleware.redirect.RedirectMiddleware',
    'openidconsumer.middleware.OpenIDMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'middleware.ajax_errors.AjaxMiddleware',
    'pingback.middleware.PingbackMiddleware',
    'localeurl.middleware.LocaleURLMiddleware', 
    'multilingual.flatpages.middleware.FlatpageFallbackMiddleware',
    'django.middleware.common.CommonMiddleware',
)

但是,尽管我的OS&浏览器设置是西班牙语。

LANGUAGES = (
    ('en', ugettext('English')),  
    ('es', ugettext('Spanish')),
)
DEFAULT_LANGUAGE = 1

然后,我破解locale-url的中间件并执行此操作:

def process_request(self, request):
    locale, path = self.split_locale_from_request(request)
    if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
        locale = utils.supported_language(request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0])
    locale_path = utils.locale_path(path, locale)

    if locale_path != request.path_info:
        if request.META.get("QUERY_STRING", ""):
            locale_path = "%s?%s" % (locale_path,
                    request.META['QUERY_STRING'])
        return HttpResponseRedirect(locale_path)
    request.path_info = path
    if not locale:
        locale = settings.LANGUAGE_CODE
    translation.activate(locale)
    request.LANGUAGE_CODE = translation.get_language()

然而,这检测到语言很好,但将“en”网址重定向到“es”。所以用英语导航是不可能的。

更新:这是最终代码(来自 Carl Meyer 的输入后),修复了“/”的情况:

def process_request(self, request):
    locale, path = self.split_locale_from_request(request)
    if (not locale) or (locale==''):
        if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
            locale = utils.supported_language(request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0])
        else:
            locale = settings.LANGUAGE_CODE
    locale_path = utils.locale_path(path, locale)
    if locale_path != request.path_info:
        if request.META.get("QUERY_STRING", ""):
            locale_path = "%s?%s" % (locale_path, request.META['QUERY_STRING'])
        return HttpResponseRedirect(locale_path)
    request.path_info = path
    translation.activate(locale)
    request.LANGUAGE_CODE = translation.get_language()

3 个答案:

答案 0 :(得分:11)

更新:django-localeurl的LocaleURLMiddleware现在直接支持HTTP Accept-Language作为后备,如果LOCALEURL_USE_ACCEPT_LANGUAGE设置为True。那么OP的所需行为现在可用而无需编写自定义中间件)。

启用Django的内置LocaleMiddleware和LocaleURLMiddleware是没有意义的。它们旨在作为相互排斥的替代方案,并且在选择语言方面具有不同的逻辑。 Locale-url在tin上执行它所说的内容:locale由URL组件定义(因此不是由Accept-Language标头定义)。 Django的LocaleMiddleware将choose the language based on a session value or cookie or Accept-Language header。启用这两者只意味着最后一个获胜,这就是您看到LocaleURLMiddleware行为的原因。

听起来好像你想要两种混合,其中初始语言(访问网站的根URL?)是基于Accept-Language选择的,然后由URL定义?现在还不完全清楚你想要什么样的行为,所以澄清这是第一步。然后,您可能需要编写自己的LocaleMiddleware来实现该行为。您第一次尝试黑客攻击LocaleURLMiddleware总是使用Accept-Language代替URL中定义的内容。相反,您需要在“if not locale:”部分中进一步检查Accept-Language标题,默认为settings.LANGUAGE_CODE。更像这样的(未经测试的代码):

def process_request(self, request):
    locale, path = self.split_locale_from_request(request)
    locale_path = utils.locale_path(path, locale)

    if locale_path != request.path_info:
        if request.META.get("QUERY_STRING", ""):
            locale_path = "%s?%s" % (locale_path, request.META['QUERY_STRING'])
        return HttpResponseRedirect(locale_path)
    request.path_info = path
    if not locale:
        if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
            locale = utils.supported_language(request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0])
        else:
            locale = settings.LANGUAGE_CODE
    translation.activate(locale)
    request.LANGUAGE_CODE = translation.get_language()

答案 1 :(得分:1)

我也需要这种行为。 你现在只使用你的自定义中间件获取语言,还是你仍然使用LocaleURLMiddleware和LocaleMiddleware结合上面代码中的中间件?

答案 2 :(得分:0)

真的应该是这样的:

可以按优先顺序接受多种语言

def process_request(self, request):
    locale, path = utils.strip_path(request.path_info)
    if (not locale) or (locale==''):
        if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
        l = [x.strip()[:2] for x in request.META['HTTP_ACCEPT_LANGUAGE'].split(',')]
        for lang_code in l:
                locale = utils.supported_language(lang_code)
                if locale:
          break
        else:
            locale = settings.LANGUAGE_CODE
    locale_path = utils.locale_path(path, locale)
    if locale_path != request.path_info:
        if request.META.get("QUERY_STRING", ""):
            locale_path = "%s?%s" % (locale_path,
                    request.META['QUERY_STRING'])
        return HttpResponseRedirect(locale_path)
    request.path_info = path
    if not locale:
        try:
            locale = request.LANGUAGE_CODE
        except AttributeError:
            locale = settings.LANGUAGE_CODE
    translation.activate(locale)
    request.LANGUAGE_CODE = translation.get_language()