In Django's documentation there's an example,在Django中设置模板语言,以显示用户如何选择页面语言。他们填写然后提交表格。
这个例子适合我。但是,我想使用带有链接列表的Bootstrap dropdown来导致此行为。我有想法设置" next"的值。输入所选语言的代码并提交表格。这是代码:
<form name="ui" action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
{% get_current_language as LANGUAGE_CODE %}
{% get_language_info for LANGUAGE_CODE as lang %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{{ lang.name_local }}
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
{% for language in languages %}
<li><a href="#" onclick="document.ui.next.value='{{ language.code}}'; document.ui.submit();">{{ language.name_local }}</a></li>
{% endfor %}
</ul>
</form>
它生成以下html代码(我省略了csrf令牌,但它就在那里):
<form name="ui" action="/i18n/setlang/" method="post">
<input name="next" type="hidden" value="" />
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">English<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#" onclick="document.ui.next.value='en'; document.ui.submit();">English</a></li>
<li><a href="#" onclick="document.uiLang.next.value='de'; document.uiLang.submit();">German</a>
</li>
</ul>
</form>
这导致(选择带有&#34; de&#34;语言代码的德语),但请求网址为http://127.0.0.1:8000/i18n/setlang/de时出现404错误(并且,请注意,不要使用请求方法&# 34; GET&#34;。)
出了什么问题,如何解决问题?
P.S。这条线
url(r'^i18n/', include('django.conf.urls.i18n')),
在urls.py
中答案 0 :(得分:3)
你可以尝试这个更简单的方法:
{% load i18n %}
{% get_available_languages as languages %}
{% for language in languages %}
<li class="{% ifequal current_language language.0 %}active{% endifequal %}">
<a href="/./{{ language.0 }}/" title="{{ language.1 }}">
{{ language.1 }}
</a>
</li>
{% endfor %}
答案 1 :(得分:3)
这对我有用:添加一个名为“language”的附加输入元素
此外,在提交表单之前,在JS中为其分配语言代码,即document..language.value =
然后模板的一部分看起来像这样:
<form name="ui" action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<input name="language" type="hidden"/>
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
{% get_current_language as LANGUAGE_CODE %}
{% get_language_info for LANGUAGE_CODE as lang %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{{ lang.name_local }}
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
{% for language in languages %}
<li><a href="#" onclick="document.ui.language.value='{{ language.code}}'; document.ui.submit();">{{ language.name_local }}</a></li>
{% endfor %}
</ul>