第三方应用程序的Django翻译。

5
我是一个有用的助手,可以翻译文本。
我正在尝试在我的Django 1.7项目中翻译一个第三方应用程序(django-recurrence)。尽管我已经阅读了关于相同问题的所有答案,但我仍然无法让Django为这个应用程序生成django.po文件。
以下是我的当前设置:
settings.py
LANGUAGE_CODE = 'it-IT'
gettext = lambda s: s
LANGUAGES = (
    ('en-us', gettext('English')),
    ('it-it', gettext('Italian')),
)

LOCALE_PATHS = (
    '/home/seether/.virtualenvs/mytime/lib/python2.7/site-packages/recurrence/locale',)

TIME_ZONE = 'Europe/Rome'

USE_I18N = True

USE_L10N = True

我已经尝试以多种方式修改 LOCALE_PATHS,例如:
LOCALE_PATHS = (os.path.join(BASE_DIR,'locale-recurrence'))
LOCALE_PATHS = (os.path.join(BASE_DIR,'locale'))
...

“等等。我手动翻译了这个应用程序的django.po文件,尝试将其复制到相应的目录中,但按照我尝试的设置,它从未起作用。我尝试将LANGUAGES和LANGUAGE_CODE更改为几乎所有可能的组合,包括:'it'、'it-it'、'it_it'、'it-IT'和'it_IT'。也没有起作用。

命令:


django-admin.py makemessages --all

只会为 Django 本身生成区域设置文件,完全忽略我想要翻译的应用程序。我也尝试使用 django-rosetta,但老实说,我不能告诉你我已经深入了这条路,因为我已经自己翻译了应用程序。基本上,我认为找到正确的方法只是告诉 Django 编译我为 django-recurrence 编写的 django.po 并使用它就足够了。

我错过了什么?

4个回答

16

我的回答试图将@catabaran提供的所有步骤编译在一起:

# From the root of your project (BASE_DIR):
# Create a symlink to the application that needs to be translated
ln -s /<path_to_virtualenv>/lib/pythonx.x/site-packages/<app> ./

# Instruct makemessages to follow the symlink
./manage.py makemessages -s

# Create a folder called "tpa_translation" 
# (Third Party Applications Translation) 
mkdir ./<proj>/tpa_translation/<app>

# Copy inside, the directory tree that springs from your language.
# This is usually located inside the locale directory 
# of the third party application.
cp -R ./<app>/locale/<your_lang> ./<proj>/tpa_translation/<app>/

# Result:
# If <your_lang> is "en", the resulting folder will be:
# f"{BASE_DIR / 'tpa_translation' / '<app>' / 'en'}"

# Set accordingly the LOCALE_PATHS in settings.py:
...
LOCALE_PATHS = [
    ...,
    f"{BASE_DIR / 'tpa_translation' / '<app>'}",
    ...,
]
...

#Remove the symlink
rm ./<app>

# Translate the .po file:
vim <proj>/tpa_translation/<app>/<your_lang>/LC_MESSAGES/django.po

# Compile messages
./manage.py compilemessages

# At this point django will message that a .mo file was created 
# inside the directory where the new .po file exists.

4
根据Django 2的文档“Django如何查找翻译”:

在LOCALE_PATHS列出的目录具有最高优先级,最先出现的具有比后来出现的更高的优先级。

只需在根目录中创建一个名为locale的文件夹,并在设置中设置LOCALE_PATHS
LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ]

我的区域设置:

$ tree locale
locale
└── ca
    └── LC_MESSAGES
        ├── django.mo
        └── django.po

(不要忘记编译消息:django-admin compilemessages

我刚测试了一下我的项目,跑得非常好。


3

你查看过安装在虚拟环境中的应用程序使用makemessages了吗?

它指出,为了让makemessages找到第三方应用程序,您需要创建一个指向该应用程序的符号链接。

我刚刚按照那个指南操作,成功地将Django REST Framework进行翻译。


2
我自己发现最简单的方法是fork模块,将其克隆到计算机上,运行一个示例项目,然后进行翻译。一旦您将这些翻译推回到您的fork仓库中,就可以使用它而不是官方版本。您可以在requirements.txt中使用git+https://github.com/my-respository.git。您也可以翻译该模块并向原始作者发送合并请求。如果您幸运的话,他们会将其合并到原始存储库中,这样您就可以切换回那个版本。
其他解决方案存在问题。例如,如果您的母语是德语,但模块是用英语编写的,则将无法获得正确的翻译。
希望这能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接