Django1.4: Generic way to set language links in template to work with i18n_patterns? Django1.4: Generic way to set language links in template to work with i18n_patterns? django django

Django1.4: Generic way to set language links in template to work with i18n_patterns?


Basically, there are two different approaches to setting the language. You can use i18n_patterns to auto-magically prefix your urls with a language code, or you can use the django.views.i18n.set_language view to change the value of the language code in the user's session (or a cookie, if your project doesn't have session support).

It's worth noting the algorithm LocaleMiddleware uses to determine language:

  • First, it looks for the language prefix in the requested URL. This is only performed when you are using the i18n_patterns function in your root URLconf. See Internationalization: in URL patterns for more information about the language prefix and how to internationalize URL patterns.

  • Failing that, it looks for a django_language key in the current user's session.

  • Failing that, it looks for a cookie.The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.)

  • Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations.

  • Failing that, it uses the global LANGUAGE_CODE setting.

The problem you're likely running into is that you can't use set_language to redirect from a url that's already being served with a language prefix, unless you specifically pass a next parameter in the POST data. This is because set_language will default to redirecting to the referrer, which will include the previous language prefix, which LocaleMiddleware will then see and serve the content in the old language (because it looks for a language prefix in the url before checking the django_language session variable).

An example, for clarity:

  1. Your user is on /en/news/article/1000, and clicks on the link which will post 'language=es' to set_language.

  2. set_language sees 'language=es', checks to see if 'es' is available, and then sets the 'django_language' session variable (or cookie) to 'es'

  3. Since you haven't set 'next', it redirects to the value of reqeuest.META['HTTP_REFERRER'], which is /en/news/article/1000

  4. LocaleMiddleware (source) sees the 'en' prefix in the url, and activates the 'en' language and sets request.LANGUAGE_CODE to 'en'

I see two possible solutions:

  1. Write your own set_language view (see the original source here), which will check for a language prefix in the referrer(use django.utils.translation.get_language_from_path), and change it to the prefix for the newly selected language before redirecting back to it.

  2. Use javascript to do the same operation client-side, and set the next POST parameter. Really this is kind of silly; it would probably be simpler to just use javascript to dynamically prepend all urls with the user's preferred language code, and forget about set_language altogether.

It seems that this new set_language view should probably be Django's default behavior. There was a ticket raised, which included a proposed implementation, but didn't really describe the problem and was subsequently closed. I suggest opening a new ticket with a better description of your use case, the problem caused by the existing set_language implementation, and your proposed solution.


Actually, there's no need to fiddle with your view. Django has a handy slice tag, so you can just use {{ request.path|slice:'3:' }} as your link URL. This lops the language code prefix off so the language is set by the set_lang function.


Having had the same problem today with Django 1.7, I devised this solution - not very DRY but it seems to work OK (and all my tests are passing, so...).Rather than using the builtin set_language view, I copied it and made one tiny adjustment - here's the result:

def set_language(request):"""Redirect to a given url while setting the chosen language in thesession or cookie. The url and the language code need to bespecified in the request parameters.Since this view changes how the user will see the rest of the site, it mustonly be accessed as a POST request. If called as a GET request, it willredirect to the page in the request (the 'next' parameter) without changingany 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 partnext = 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 URLcurrent_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 pagenext = reverse(next_data.view_name, args=next_data.args, kwargs=next_data.kwargs)# End changed partresponse = 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

To sum it up, I resolve() the view parameters for next, then pass the data to reverse() after activating the new language. Hope this helps.