这是我的解决方案:
创建 django 中间件:django_app/lib/middleware/locale.py
from django.utils import translation
class SwitchLanguageMiddleware(object):
def process_request(self, request):
lang = request.GET.get('lang', '')
if lang:
translation.activate(lang)
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
request.session['django_language'] = translation.get_language()
if 'Content-Language' not in response:
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
读取request的get参数,如果有lang属性,则切换语言。例如:/about-us/?lang=pl
将此中间件包含到 settings.py 中:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.common.CommonMiddleware',
'django_app.libs.middleware.locale.SwitchLanguageMiddleware',
)