Reputation: 11
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
Upvotes: 0
Views: 168
Reputation: 11
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))
Upvotes: 1