Django-在GET之后将用户重定向到特定视图,更改语言设置 [英] Django - redirecting a user to a specific view after GET to a separate view, changing language settings
问题描述
我有一个网站,提供2种语言选择-英语和英语;日本。
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.
当前路径作为url参数传递,然后保存到响应变量,然后在返回之前设置它的语言cookie。
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.
由于某种原因,当我在 redirect中使用参数时
函数,根本没有设置语言cookie,而是使用 reverse
(即,当它被硬编码返回家中时)工作正常。
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
?
谢谢!
代码:
模板链接:
<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>
网址:
path('lang /
查看:
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
推荐答案
我找到了解决上述问题的方法。
通过将 {{request.resolver_match.url_name}}
添加到标签的查询参数中,然后称为 reverse $ c来修复$ c>在视图中的该查询参数上:
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:
链接:
< ; a href = {%url'language''en'%}?q = {{request.path}} class = lang-choice btn btn-primary>英语< / a>
至:
< a href = {%url'语言''en'%}?q = {{request.resolver_match.url_name}} class = lang-choice btn btn-primary>英语< / a>
然后重构视图:
response = redirect(redirect_page)
收件人:
response = redirect(reverse(reverse(redirect_url_name))
这篇关于Django-在GET之后将用户重定向到特定视图,更改语言设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!