官方原文:
国际化与本地化的目的为了能为各个不同的用户以他们最熟悉的语言和格式来显示网页。
Django能完美支持文本翻译、日期时间和数字的格式化、时区。
另外,Django还有两点优势:
- 允许开发者和模板作者指定他们哪些app应该被翻译或被格式化为本地形式。
- 允许用户根据自己的偏好来实现本地化显示。翻译依据语言,格式化依据国家, 这些信息由浏览器中的
Accept-Language
头来决定。不过目前为止时区还未能实现
配置
实际上django的国际化做的非常好了,配置很简单。
settings.py
首先在settings中,添加如下内容:
from django.utils.translation import ugettext_lazy as _LOCALE_PATH = { os.path.join(BASE_DIR, 'locale')}LANGUAGES = ( ('en', _('English')), ('zh-cn', _('Simplified Chinese')))LANGUAGE_CODE = 'zh-hans'TIME_ZONE = 'Asia/Shanghai'USE_I18N = True
通过LANGUAGES
执行语言列表,LOCALE_PATHS
指定国际化目录。
翻译
在项目根目录下面创建一个locale文件夹,然后使用命令创建国际化文件:
python manage.py makemessages -l zn_CN
执行完后,locale文件夹下面创建zh_CN/LC_MESSAGES/django.po
,里面的内容类似下面:
# 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, YEAR.##, fuzzymsgid ""msgstr """Project-Id-Version: PACKAGE VERSION\n""Report-Msgid-Bugs-To: \n""POT-Creation-Date: 2017-03-14 15:51+0800\n""PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n""Last-Translator: FULL NAME \n""Language-Team: LANGUAGE \n""Language: \n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"#: .\categories\admin.py:17 .\forum\admin.py:15msgid "is visible"msgstr ""#: .\categories\models.py:18msgid "parent category"msgstr ""#: .\categories\models.py:20msgid "name"msgstr ""#: .\categories\models.py:21 .\covers\models.py:14 .\covers\models.py:27#: .\covers\models.py:28msgid "cover"msgstr ""#: .\categories\models.py:23 .\forum\models.py:36msgid "slug"msgstr ""#: .\categories\models.py:24msgid "description"msgstr ""#: .\categories\models.py:30 .\categories\models.py:31 .\forum\models.py:40msgid "category"msgstr ""#: .\config\settings.py:140msgid "English"msgstr ""#: .\config\settings.py:141msgid "Simplified Chinese"msgstr ""#: .\covers\models.py:16msgid "caption"msgstr ""#: .\forum\models.py:34msgid "title"msgstr ""#: .\forum\models.py:35msgid "body"msgstr ""#: .\forum\models.py:37msgid "views"msgstr ""#: .\forum\models.py:38msgid "pinned"msgstr ""#: .\forum\models.py:41msgid "author"msgstr ""#: .\forum\models.py:42msgid "tags"msgstr ""#: .\forum\models.py:44 .\replies\models.py:12msgid "replies"msgstr ""#: .\forum\models.py:50msgid "post"msgstr ""#: .\forum\models.py:51msgid "posts"msgstr ""#: .\replies\models.py:11msgid "reply"msgstr ""
将你上面需要翻译的内容写到这里面来即可。比如name
要翻译成名称
。
编译翻译
写好了所有的翻译后,再执行:
python manage.py compilemessages
这时候会生成文件zh_CN/LC_MESSAGES/django.mo
,这个是最终的目标文件了。