From df1ad561b124450388a696e668fa6549f2bbe446 Mon Sep 17 00:00:00 2001 From: Jannis Leidel Date: Tue, 16 Feb 2010 12:52:04 +0000 Subject: [PATCH] [1.1.X] Fixed #7720 - Fallback to the base language if the sub language given in the language cookie doesn't exist. Thanks, djoume and Ramiro Morales. Backport of r12442. git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.1.X@12452 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/utils/translation/trans_real.py | 4 ++++ tests/regressiontests/i18n/misc.py | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index 6e7fb8cf50..74214735ef 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -354,6 +354,10 @@ def get_language_from_request(request): return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) + + if lang_code and lang_code not in supported: + lang_code = lang_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr + if lang_code and lang_code in supported and check_for_language(lang_code): return lang_code diff --git a/tests/regressiontests/i18n/misc.py b/tests/regressiontests/i18n/misc.py index 7a82af0050..0a5b10cbc0 100644 --- a/tests/regressiontests/i18n/misc.py +++ b/tests/regressiontests/i18n/misc.py @@ -85,6 +85,21 @@ source tree. >>> r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-ar,de'} >>> g(r) 'es-ar' + +# Now test that we parse language preferences stored in a cookie correctly. +>>> from django.conf import settings +>>> r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'} +>>> r.META = {} +>>> g(r) +'pt-br' +>>> r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt'} +>>> r.META = {} +>>> g(r) +'pt' +>>> r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es'} +>>> r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'} +>>> g(r) +'es' """ # Python 2.3 and 2.4 return slightly different results for completely bogus @@ -98,9 +113,14 @@ This test assumes there won't be a Django translation to a US variation of the Spanish language, a safe assumption. When the user sets it as the preferred language, the main 'es' translation should be selected instead. +>>> r.COOKIES = {} >>> r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-us'} >>> g(r) 'es' +>>> r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es-us'} +>>> r.META = {} +>>> g(r) +'es' """ tests += """ @@ -108,7 +128,12 @@ This tests the following scenario: there isn't a main language (zh) translation of Django but there is a translation to variation (zh_CN) the user sets zh-cn as the preferred language, it should be selected by Django without falling back nor ignoring it. +>>> r.COOKIES = {} >>> r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-cn,de'} >>> g(r) 'zh-cn' +>>> r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'zh-cn'} +>>> r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'} +>>> g(r) +'zh-cn' """