from django.utils.cache import patch_vary_headers from django.utils import translation from django.http import HttpResponseRedirect from django.conf.settings import DEBUG from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('de', _('German')), ('en', _('English')), ('fr', _('French')), ('es', _('Spanish')), ('zh-cn', _('Simplified Chinese')), ('zh-tw', _('Traditional Chinese')), ('ko', _('Korean')), ) LANGUAGE_MAP = { 'zh-cn': 'cn', 'zh-tw': 'tw', } LANGUAGES_DICT = dict(LANGUAGES_SHORT) class LocaleMiddleware(object): def validate_language(self, request, language): # If DEBUG mode is enabled just set the language to en so we dont have to worry about redirects on our runserver if DEBUG: translation.activate('en') return host = request.META.get('HTTP_HOST').split('.') # If only the domain is requested redirect to www. if len(host) == 2: return HttpResponseRedirect('http://www.%s' % request.META['HTTP_HOST']) host_path = host[0].split('-') lang_code = len(host_path) >= 2 and '-'.join(host_path[1:]) or None # Validate the language selected if not lang_code or len(lang_code) > 2: if lang_code in LANGUAGE_MAP: lang_code = LANGUAGE_MAP[language] elif lang_code not in LANGUAGES_DICT: lang_code = 'en' return HttpResponseRedirect('http://%s-%s.%s%s' % (host_path[0], lang_code, '.'.join(host[-2:]), request.path)) # If the language is CN or TW set it to the proper language. We could probably just reverse our LANGUAGE_MAP # dictionary to do this automatically if lang_code == 'cn': real_lang_code = 'zh-cn' elif lang_code == 'tw': real_lang_code = 'zh-tw' else: real_lang_code = lang_code # Store this in the session if it's not already set if translation.check_for_language(real_lang_code): if hasattr(request, 'session') and request.session.get('django_language', None) != real_lang_code: request.session['django_language'] = real_lang_code request.LANGUAGE_CODE = lang_code language = translation.get_language_from_request(request) if not language: language = 'en' translation.activate(language) # If for some reason the language we activated doesn't match our real language requested we redirect to the language activated if language != real_lang_code: return HttpResponseRedirect('http://%s-%s.%s%s' % (host_path[0], language, '.'.join(host[-2:]), request.path)) def process_request(self, request): language = translation.get_language_from_request(request) return self.validate_language(request, language) def process_response(self, request, response): #patch_vary_headers(response, ('Accept-Language',)) response['Content-Language'] = translation.get_language() translation.deactivate() return response