1

在这上面花了太多时间之后,StackOverflow 是为了救援。

我将我的 settings.py 配置如下:

...
TIME_ZONE = 'Europe/Berlin'

LANGUAGE_CODE = 'de'

LANGUAGES = (
  ('en', u'English'),
  ('de', u'German'),
  ('fr', u'French'),
)

USE_I18N = True

USE_L10N = True

MIDDLEWARE_CLASSES = (
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

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

在我的base.html文件中,我有一个如下表格:

<form action="/i18n/setlang/" method="post">
    {% csrf_token %}
    <input name="next" type="hidden" value="/" />
    <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('',
    url(r'^i18n/', include('django.conf.urls.i18n')),
    url(r'^$', 'MainApp.views.index'), #root
)

在同一个base.html文件中,我在顶部{% load i18n %}和正文中有一个示例{% trans "This is the title." %}. 在运行服务器之前,我做了:

django-admin.py makemessages -l de
django-admin.py makemessages -l fr

上面的示例文本是由 提取的makemessages,我提供了相应的翻译msgstr。之后,我执行了django-admin.py compilemessages.该命令运行良好并在相应的语言环境文件夹中生成了.mo文件。

我运行服务器并且表单不起作用。在另一篇 StackOverflow 帖子中,有人提示我删除#, fuzzy lines,我这样做了。我究竟做错了什么?

谢谢!

4

1 回答 1

1

您应该在 MIDDLEWARE_CLASSESLocaleMiddleware之后添加:SessionMiddleware

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
....
)

中间件类的顺序很重要。使用LocaleMiddleware会话数据来检测用户语言,所以它必须在SessionMiddleware. 此处的文档中也提到了它https://docs.djangoproject.com/en/1.3/topics/i18n/deployment/#how-django-discovers-language-preference

希望这对您有用!

于 2013-08-12T22:27:51.700 回答