How to use django.views.i18n.set_language() function?

╄→尐↘猪︶ㄣ 提交于 2019-12-06 07:48:40

问题


I read a tutorial in Django site but I don't understand how to use the set_language() function. For example, I have a demo follow as:

index.html

{% trans "Hello World." %}

<form action="/i18n/setlang/" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="/next/page/" />
<select name="language">
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}">{{ language.name_local }} ({{ language.code}})</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>

urls.py

urlpatterns = patterns('',
    (r'^i18n/', include('django.conf.urls.i18n')),
)

views.py

What need I write to display the languages, which were chosen from user in this file?

Thanks,

Thinh


回答1:


With the code you are using, you don't need to write your own views. The form will make a POST request to /i18n/setlang/, with the language code and (optional) the redirect-to (next) page as parameters.

The django view does the following (from the django documentation)

Django looks for a next parameter in the POST data. - If that doesn't exist, or is empty, Django tries the URL in the Referrer header. - If that's empty -- say, if a user's browser suppresses that header -- then the user will be - redirected to / (the site root) as a fallback.

So in essence, the user will be redirected after submitting the form, and the django view will set the language for that user according to what was submitted.

Hope this helps,

Hoff



来源:https://stackoverflow.com/questions/6993689/how-to-use-django-views-i18n-set-language-function

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