Django url更改语言代码

时间:2017-03-12 08:10:48

标签: python django django-i18n

当用户点击Django中的按钮时,我正在尝试更改网站的语言。

我有一个基础项目,网址是:

urlpatterns += i18n_patterns(
    # Ecommerce is the app where I want to change the language
    url(r'^', include("ecommerce.urls")),
)

Ecommerce.urls中的网址是:

urlpatterns = [
    url(r'^testing/$', views.test, name='url_testing'),
    ... other urls
]

当我访问上面的网址时,我首先访问:http://localhost/en/testing/

我想设置一个链接<a href="{% url 'url_testing' %}">Change Language</a>,以便当用户点击它时,它会将语言更改为http://localhost/zh-hans/testing/。我如何在模板中执行此操作?

修改

我现在可以使用以下代码更改语言,但问题是它只能运行一次:

<form id="languageForm" action="/i18n/setlang/" method="post">
    {% csrf_token %}
    <input name="next" type="hidden" value="{% url 'url_testing' %}" /> 
    <input id="newLanguageInput" type="hidden" name="language"/>
</form>

我的链接是:

<li><a onclick="changeLanguage('zh-hans')">简体</a></li>
<li><a onclick="changeLanguage('zh-hant')">繁體</a></li>

函数changeLanguage定义如下:

function changeLanguage(newLanguage) {
    $('input[name="newLanguageInput"]').val(newLanguage);
    $('#languageForm').submit();
}

当我第一次点击2个链接中的任意一个时,代码就会生效,我将被重定向到网址http://localhost/zh-hans/testing/http://localhost/zh-hant/testing/。问题是在我更改语言一次后,它不再发生变化。我的提交有问题吗?

2 个答案:

答案 0 :(得分:3)

实际上它不是一个简单的<a>链接,而是一个<form>

阅读how to set_language redirect view。此表单将负责更改语言。这很简单。

确保先设置了一些LANGUAGES

答案 1 :(得分:0)

当用户点击链接(没有网址翻译,没有帖子)时,您可以更改网站的语言,如下所示:

navigation.html(使用bootstrap4和字体很棒)

<li class="nav-item dropdown">
  {% get_current_language as LANGUAGE_CODE %}
  <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown">{{ LANGUAGE_CODE }}</a>
  <div class="dropdown-menu dropdown-menu-right">

    {% get_available_languages as languages %}
    {% for lang_code, lang_name in languages %}

    <a href="{% url 'main:activate_language' lang_code %}" class="dropdown-item">
      {% if lang_code == LANGUAGE_CODE %}
        <i class="fas fa-check-circle"></i>&nbsp;&nbsp;
      {% else %}
        <i class="far fa-circle"></i>&nbsp;&nbsp;
      {% endif %}
      {{ lang_name }} ({{ lang_code }})
    </a>

    {% endfor %}
  </div>
</li>

views.py

from django.shortcuts import redirect
from django.utils import translation
from django.views.generic.base import View

class ActivateLanguageView(View):
    language_code = ''
    redirect_to   = ''

    def get(self, request, *args, **kwargs):
        self.redirect_to   = request.META.get('HTTP_REFERER')
        self.language_code = kwargs.get('language_code')
        translation.activate(self.language_code)
        request.session[translation.LANGUAGE_SESSION_KEY] = self.language_code
        return redirect(self.redirect_to)

urls.py

from django.urls import path
from .views import ActivateLanguageView

app_name = 'main'
urlpatterns = [
    path('language/activate/<language_code>/', ActivateLanguageView.as_view(), name='activate_language'),
]

这对我有用。