我想用英语和西班牙语部署一个网站,并检测用户浏览器语言并重定向到正确的语言环境站点。
我的网站是 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',
)
但是,尽管我的操作系统和浏览器设置是西班牙语,但网站总是会到达美国。
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()