切换语言时 Django 国际化没有正确重定向?

Django internationalization isn't redirecting correctly when switching language?

我对一个网站进行了国际化,并且通过访问具有不同语言前缀的相同 URL 进行翻译,即 /en/home 和 /de/home 使用其各自的语言。

但是,当使用 Django built-in view setlang 切换语言时,我总是在不更改语言前缀的情况下返回重定向 URL,即在 /en/home 并且切换到德语应该重定向到/de/home/,但我得到的是 /en/home

进行一些调试,并在 Django 中四处寻找,我发现名为 translate_url() 的函数没有正确返回正确的 url。不幸的是,更深入对我来说有点毛茸茸,我正在扯掉我的头发。单击上面的函数名称会给出给我问题的确切行。

有人知道哪里出了问题吗?

urls.py:

urlpatterns = [
    url(r'^i18n/', include('django.conf.urls.i18n')),
    url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += i18n_patterns(
    url(r'^', include('website.urls')),
)

website/urls.py:

urlpatterns = [
    url(r'^contact/$',
        ContactFormView.as_view(form_class=CustomContactForm),
        name='contact_form'),
    url(r'^contact/sent/$',
        TemplateView.as_view(
            template_name='contact_form/contact_form_sent.html'),
        name='contact_form_sent'),
    url(r'^$', TemplateView.as_view(template_name="website/home.html")),
]

模板:

{% load staticfiles %}
{% load i18n %}
{% load website_tags %}
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES_AVAILABLE %}

            <form action="{% url 'set_language' %}" method="post">
                <div class="language_choice">
                    <label for="language">Language</label>
                    <div class="lang_drp">
                        {% csrf_token %}
                        <select name="language" id="language">
                            {% for code, name in LANGUAGES_AVAILABLE %}
                            <option value="{{ code }}" {% if code == LANGUAGE_CODE %}selected{% endif %}>{{ name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </form>

settings.py:

# MIDDLEWARE CONFIGURATION
# -----------------------------------------------------------------------------
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# TEMPLATE CONFIGURATION
# -----------------------------------------------------------------------------
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(APPS_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
            ],
        },
    },
]

# LANGUAGE CONFIGURATION
# -----------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/topics/i18n/
USE_I18N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'de'

# Language name string is always native, that is to ensure that if reader don't
# understand the current language displayed, the user would still be able to
# recognize the native name of their language.
LANGUAGES = [
    ('en', 'English'),
    ('de', 'Deutsch'),
]

LOCALE_PATHS = [
    os.path.join(APPS_DIR, 'locale'),
]

所以我发现了问题。显然,您必须包含一个对应于当前路径(没有语言前缀)的下一个 parameter/input 字段,以便重定向工作。

我错误地认为,这是 Django 自动计算出来的。

使用 django-modeltranslation 更改语言后重定向到主页?

如果要重定向到同一页面,可以替换这部分代码:

index.html:

{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}: </p>
  <ul class="languages">
    {% for language in languages %}
      <li>
        <a href="/{{ language.code }}/
          {% if language.code == LANGUAGE_CODE %} class="selected"{% endif %}>
          {{ language.name_local }}
        </a>
      </li>
    {% endfor %}
  </ul>
</div>

至:

{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}: </p>
  <ul class="languages">
    {% for language in languages %}
      <li>
        <a href="/{{ language.code }}/{{request.get_full_path|slice:"4:"}}"
          {% if language.code == LANGUAGE_CODE %} class="selected"{% endif %}>
          {{ language.name_local }}
        </a>
      </li>
    {% endfor %}
  </ul>
</div>

请注意:

<a href="/{{ language.code }}/

替换为 <a href="/{{ language.code }}/{{request.get_full_path|slice:"4:"}}"