Django语言更改不起作用

Tus*_*usk 2 python django cookies internationalization rosetta

我正在使用Django 1.6,感觉好像缺少一些东西,但是cookie设置为当前选择的语言,但显示语言保持默认。

对应代码:

settings.py

LANGUAGES = (
    ('hu', 'Hungarian'),
    ('en', 'English'),
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request"
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
)
LANGUAGE_CODE = 'en-US'
TIME_ZONE = 'CET'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Run Code Online (Sandbox Code Playgroud)

urls.py

urlpatterns = patterns('',
    url(r'^i18n/', include('django.conf.urls.i18n')),
    ...
)
Run Code Online (Sandbox Code Playgroud)

模板

{% extends 'base.html' %}
{% load i18n %}
...
<h4>{% trans "Modern Technologies" %}</h4>
...
Run Code Online (Sandbox Code Playgroud)

我运行了makemessages -a来创建lang文件,安装了rosetta并编辑了语言。然后我运行了编译消息。在Chrome中检入cookie“ django_language”的设置正确。但是实际的文本仍然是默认的“现代技术”。

Lud*_*mer 7

您的中间件顺序与文档建议的顺序不同:

要使用LocaleMiddleware,请将'django.middleware.locale.LocaleMiddleware'添加到您的MIDDLEWARE_CLASSES设置中。因为中间件顺序很重要,所以您应遵循以下准则:

  • 确保它是安装的第一个中间件之一。
  • 它应该出现在SessionMiddleware之后,因为LocaleMiddleware使用了会话数据。它也应该在CommonMiddleware之前出现,因为CommonMiddleware需要一种激活的语言才能解析请求的URL。
  • 如果使用CacheMiddleware,请将LocaleMiddleware放在其后。

因此,您的中间件配置应如下所示:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Run Code Online (Sandbox Code Playgroud)

您还需要记住在设置文件中包括LOCALE_PATHS设置:

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
Run Code Online (Sandbox Code Playgroud)