试图弄清楚Django i18n是如何工作的。已经阅读了官方和其他几个教程。问题是Django生成.po文件,但它不包含来自我的模型和Python脚本的消息(好吧,我已准备好使用脚本,但模型必须翻译)。以下是我的设置:
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
os.path.join(BASE_DIR, 'install', 'locale'),
]
LANGUAGES = (
('ru', _('Russian')),
('en', _('English')),
)
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
LANGUAGE_CODE = 'en'
这是.po文件(' locale'文件夹位于项目的根目录中):
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-05-12 12:26-0400\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%"
"10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%"
"100>=11 && n%100<=14)? 2 : 3);\n"
#: trackpost/settings.py:127
msgid "Russian"
msgstr ""
#: trackpost/settings.py:128
msgid "English"
msgstr ""
如您所见,它仅包含设置中的字符串。在模型中,我使用ugettext_lazy as _
。
现在已经和它斗争了3天了。任何想法为什么会发生这种情况?
UPD。我翻译了一些变量。其中一个看起来像v = 'string'
然后是_(v)
,另一个是我通过API获得的文本变量。 Django没有发现它们,尽管第一个应该是。
UPD。这是项目结构(错过迁移等不重要的文件):
├── account
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── binder.py
├── db.sqlite3
├── install
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── locale
│ │ └── ru
│ │ └── LC_MESSAGES
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── locale
│ └── ru
│ └── LC_MESSAGES
│ └── django.po
├── manage.py
├── nginx.conf
├── nohup.out
├── payments.py
├── trackpost
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── uwsgi.ini
答案 0 :(得分:1)
您应该更新LOCALE_PATHS
列表,以包含包含待翻译模型的应用的locale
目录。
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
os.path.join(BASE_DIR, 'myapp', 'locale'), # translation lookup directory for "myapp" app
os.path.join(BASE_DIR, 'another_app', 'locale'), # translation lookup directory for "another_app" app
]
然后,您应该在应用程序下手动创建区域设置结构,如下所示:
myapp/locale/ru/LC_MESSAGES/
然后,运行./manage.py makemessages --all
,它将在locale
内声明的每个LOCALE_PATHS
目录下查看,并在那里创建.po
文件。你知道其余的(./manage.py compilemessages
)。