Django翻译创建po和mo文件,但在翻译中失败并显示翻译占位符

时间:2014-06-13 14:03:15

标签: python django internationalization

我正在使用带有virtualenv(Vitrual Environment)的Django 1.6.5和apache2

我有以下settings.py结构:

from django.utils.translation import ugettext_lazy as _

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 = 'tr_TR'
LANGUAGE_COOKIE_NAME = 'wm_lang'
LOCALE_PATHS = (
    '/home/mustafa/python/myproject/locale'
)

USE_I18N = True
USE_L10N = True

LANGUAGES = (
    ('tr', _(u'Türkçe')),
    ('en', _(u'English')),
)

我有一个类似

的模板文件
{% extends .... %}
{% load i18n %}

{% block content %}
    <h2>{% trans 'Hosgeldin' %}</h2>
....
....

我运行以下内容来创建po个文件

django-admin.py makemessages  --locale=tr --locale=en

创建以下文件

/home/mustafa/python/myproject/locale/tr/LC_MESSAGES/django.po
/home/mustafa/python/myproject/locale/en/LC_MESSAGES/django.po

我应用翻译字符串,以便我的django.po翻译文件看起来像那样

EN

#: templates/websitesi/index.html:6
msgid "Hosgeldin"
msgstr "Welcome, that is a test"

TR

#: templates/websitesi/index.html:6
msgid "Hosgeldin"
msgstr "Hoşgeldiniz, bu bir deneme"

然后我用

编译它们
django-admin.py compilemessages

和django为这两种语言的django.mo文件附近创建django.po个文件。

但是当我访问该页面时,我看到Hosgeldin(翻译占位符)而不是翻译文本。

将{{LANGUAGE_CODE}}写入模板会显示所选的语言代码。当我的地址为someadress/en时,语言代码显示为en ...

我错过了什么?

更新:这是 root urls.py

的一部分
urlpatterns = patterns('',
    (r'^i18n/', include('django.conf.urls.i18n')),
)

urlpatterns += i18n_patterns('',
    url(r'^admin/docs/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

urlpatterns += staticfiles_urlpatterns()

urlpatterns += i18n_patterns('websitesi.views',
    url(r'^$', 'index', name='index'),  # This is my home page
                         ....
                         ....

然后我转到my_local_server/my_local_server/trmy_local_server/en进行测试,但所有内容都无法翻译。

当我通过my_local_server/tr/adminmy_local_server/en/admin进入管理员时,django trqnslations工作得很好。

1 个答案:

答案 0 :(得分:5)

最后,正如预期的那样,它被证明是一个错字。

settings.py

LOCALE_PATHS = (
    '/home/mustafa/python/myproject/locale'
)

但是Django希望LOCALE_PATHS成为 tuple ,所以添加逗号可以解决问题......

LOCALE_PATHS = (
    '/home/mustafa/python/myproject/locale',
)