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

寵の児 提交于 2019-12-03 12:51:46

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.

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 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

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.

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.

user1039384

My apologies for the long delay. Thank you all for your answers.

First of all to comment on the two solution options by Chris: Neither custom set_language nor javascript are good for the purpose as the whole beauty of url patterns is being SEO friendly.

Furthermore, simply replacing the prefix language in URL cannot be treated as full solution for urlpattern based urls as the whole URL might be translatable too. Ex: /en/profile/ for english and /fr/profil/ for french. To solve such a problem one needs to capture the viewfunc and the arguments in order to reverse it for different language.

Fortunately for me, my project does not use translatable URLs for now and I took the following approach.

  1. Add django.core.context_processors.request to TEMPLATE_CONTEXT_PROCESSORS so that request to be available in template rendering context.

  2. Use RequestContext in views when rendering your views. This is always the case for me independent of the topic.

  3. Write a quite simple templatetag that requires the context and takes an argument a language code to return the current URL in the given language. It basically makes sure the current URL has valid language-code prefix and simply returns another string that is the same current URL with replaced language-code.

ex:

from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def get_current_url_for_lang(context, lang_code):
    request=context.get('request',False)
    if not request:
        return None

    request=context['request']
    curr_url=request.path
    if len(curr_url) < 4 or curr_url[0] != '/' or curr_url[3] != '/':
        return curr_url

    if context.get('LANGUAGES',False):
        codes = []
        for code,name in context['LANGUAGES']:
            codes.append(code)

        curr_langcode = curr_url[1:3]
        if lang_code not in codes or curr_langcode not in codes:
            return curr_url

    changed_url = '/'+lang_code+curr_url[3:]
    return changed_url

Furthermore, if one does not like to inject full request into context it will be quite straightforward to write your own context_processor that simply pushes the request.path as current_url_path for instance and use that instead in your templatetag.

Your comments are welcomed as always!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!