Django i18n_patterns: resolve() doesnt work as expected

前端 未结 1 645
不思量自难忘°
不思量自难忘° 2021-01-20 01:44

After solving this problem here, there\'s another one: if you use the translation url system here https://docs.djangoproject.com/en/1.8/topics/i18n/translation/ you will see

相关标签:
1条回答
  • 2021-01-20 02:27

    Django's url resolvers only work on current language. So you will need to switch language before attempting to solve an url in a specific language, using translation.activate.

    For resolving the url, that means you must know the language beforehand, switch to it and only then resolve (basically what the localemiddleware will do for you).

    For reversing the url, that means you should probably reverse the url using its name. You'll get back the url in current language. I cannot test right now, but it should work like this:

    from django.utils import translation
    translation.activate('fr')
    reverse('produits_index')    # /fr/produits/
    translation.activate('en')
    reverse('produits_index')    # /en/products/
    

    If you did manage to get a ResolverMatch object, you have the url name as an attribute on it, conveniently named url_name.

    I hope it helps, I am a bit unclear as to what you are trying to do. Feel free to comment/edit your question and I'll try to update this answer.


    Update by Olivier Pons


    Here's the working solution:

    here's my working solution, which is close to spectras, but works the way I wanted:

    # (!) resolve() use current language
    #     -> try to guess language then activate BEFORE resolve()
    lg_curr = translation.get_language()
    lg_url = get_language_from_path(url) or lg_curr
    translation.activate(lg_url)
    try:
        resolve(url)
        req.session['url_back'] = url  # no error -> ok, remember this
    except Resolver404:
        pass
    translation.activate(lg_curr)
    

    ...and then later on, after successful registration/login, if there's a req.session['url_back'] then I remove it from session and make a redirect on it.

    0 讨论(0)
提交回复
热议问题