Django - redirecting a user to a specific view after GET to a separate view, changing language settings

这一生的挚爱 提交于 2020-03-05 05:04:16

问题


I have a site with that offers 2 language choices - English & Japanese.

To change between the languages, A user clicks a button taking them to a view which changes the setting. Previously, it had always redirected to the home page but now I want to take them to where they were before.

The current path is passed as a url param which is then saved to a response variable, which then has it's language cookie set before being returned.

For some reason, when I use the parameter in the redirect function, the language cookie doesn't set at all but using reverse (i.e. when it was hard coded to go back home) wass working fine.

How do I get the redirect function with the param to work like the one set with reverse?

Thanks in advance!

Code:

Template Links:

<a href="{% url 'language' 'en' %}?q={{ request.path }}" class="lang-choice btn btn-primary">English</a>
<a href="{% url 'language' 'ja' %}?q={{ request.path }}" class="lang-choice btn btn-info">日本語</a>

Urls:

path('lang/<str:language>/', v.change_language, name='language')

View:

def change_language(request, language): # language is 'en' or 'ja'
    redirect_page = request.GET.get('q') # e.g. '/about/'
    # note: redirect_page == reverse('about') is True

    # make sure language is available
    valid = False
    for l in settings.LANGUAGES:
        if l[0] == language:
            valid = True
    if not valid:
        raise Http404(_('選択した言語は利用できません'))

    # Make language the setting for the session
    translation.activate(language)
    response = redirect(redirect_page) # Changing this to use reverse works

    response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)
    return response

回答1:


I found a workaround to the above problem. Fixed by adding the {{ request.resolver_match.url_name }} to the a tag's query param and then called reverse on that query param within the view:

Link:

<a href="{% url 'language' 'en' %}?q={{ request.path }}" class="lang-choice btn btn-primary">English</a>

to:

<a href="{% url 'language' 'en' %}?q={{ request.resolver_match.url_name }}" class="lang-choice btn btn-primary">English</a>

The view is then refactored:

response = redirect(redirect_page)

To:

response = redirect(reverse(redirect_url_name))



来源:https://stackoverflow.com/questions/56739938/django-redirecting-a-user-to-a-specific-view-after-get-to-a-separate-view-cha

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