今天和Django 1.7有同样的问题,我设计了这个解决方案 - 不是非常干,但它似乎工作正常(所有的测试都通过了,所以...)。 而不是使用内置set_language视图,我复制它和由一种微小的调整 - 在这里是结果:
def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
lang_code = request.POST.get('language', None)
# Start changed part
next = urlparse(next).path # Failsafe when next is take from HTTP_REFERER
# We need to be able to filter out the language prefix from the next URL
current_language = translation.get_language_from_path(next)
translation.activate(current_language)
next_data = resolve(next)
translation.activate(lang_code) # this should ensure we get the right URL for the next page
next = reverse(next_data.view_name, args=next_data.args, kwargs=next_data.kwargs)
# End changed part
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session[LANGUAGE_SESSION_KEY] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN)
return response
概括起来讲,我解决()为下一个视图参数,然后传递数据到反向()激活新语言后。希望这可以帮助。
关于将set_language与i18n_patterns一起使用,我认为您可以添加自定义中间件类,以便在请求上下文中添加不带语言前缀的URL。我试图编写一个简单的Middleware类[在这里](http://machakux.appspot.com/blog/17010/django_using_i18n_patterns_and_locale_switcher)。 – machaku 2012-06-14 18:57:57