如何使用 django.views.i18n.set_language() 函数?

发布于 2024-11-28 18:23:54 字数 1048 浏览 0 评论 0原文

我在 Django 站点中阅读了教程 /a> 但我不明白如何使用 set_language() 函数。例如,我有一个演示如下:

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?

谢谢,

Thinh

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦太阳 2024-12-05 18:23:54

使用您正在使用的代码,您不需要编写自己的视图。该表单将向 /i18n/setlang/ 发出 POST 请求,并以语言代码和(可选)重定向到(下一个)页面作为参数。

django 视图执行以下操作(来自 django 文档)

Django 在 POST 数据中查找下一个参数。
- 如果不存在或者为空,Django 会尝试 Referrer 标头中的 URL。
- 如果它是空的 - 比如说,如果用户的浏览器禁止该标头 - 那么用户将被 - 重定向到 / (站点根目录)作为后备。

因此本质上,用户在提交表单后将被重定向,并且 django 视图将根据提交的内容为该用户设置语言。

希望这有帮助,

霍夫

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文