Django国际化

本文在django 1.7验证过

1 在项目settings.py中添加两行(+表示添加行):

 Python | 
 
 copy code |
?

01
02
+ LOCALE_PATHS = (BASE_DIR+ "/locale",)
03
 
04
MIDDLEWARE_CLASSES = ( 
05
    'django.middleware.common.CommonMiddleware',
06
    'django.contrib.sessions.middleware.SessionMiddleware',
07
+   'django.middleware.locale.LocaleMiddleware',
08
    'django.middleware.csrf.CsrfViewMiddleware',
09
10

2 在views.py中标记要翻译的字符串,格式为{% trans ‘字符串’%} 如

 HTML | 
 
 copy code |
?

1
{% load i18n %}
2
<!-- 在页面最顶端加上load i18n-->
3
<!DOCTYPE html>
4
<!-- 其他内容略去-->
5
<li id="menu-item-1810" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children"><a href="/ui/users/login">{% trans 'User' %}</a>
6
</li>
7

3 建立locale目录结构

 Bash | 
 
 copy code |
?

1
2
$ mkdir locale/en -p
3
$ mkdir locale/zh_CN -p
4
$ python manage.py makemessages -a
5
processing locale zh_CN
6
processing locale en
7

此时会新建./locale/{lang}/LC_MESSAGES/django.po文件,lang表示语言,中文为zh_CN。
其中django.po文件包含了django目录中所有需要翻译的字符串。如
 Bash | 
 
 copy code |
?

01
02
#, fuzzy
03
msgid ""
04
msgstr ""
05
"Project-Id-Version: PACKAGE VERSION\n"
06
"Report-Msgid-Bugs-To: \n"
07
"POT-Creation-Date: 2016-04-07 10:33+0800\n"
08
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
09
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
10
"Language-Team: LANGUAGE <LL@li.org>\n"
11
"Language: \n"
12
"MIME-Version: 1.0\n"
13
"Content-Type: text/plain; charset=UTF-8\n"
14
"Content-Transfer-Encoding: 8bit\n"
15
 
16
#: templates/base.html:138
17
msgid "User"
18
msgstr ""
19

4 翻译相关语言下的django.po。对于每个msgid的字符串,修改对应的翻译语句,如上例为

 Bash | 
 
 copy code |
?

1
2
#: templates/base.html:138
3
msgid "User"
4
msgstr ""
5

5 编译:

 Bash | 
 
 copy code |
?

1
$ python manage.py compilemessages 
2
processing file django.po in /usr/src/appstoreserver/appstore/locale/zh_CN/LC_MESSAGES
3
processing file django.po in /usr/src/appstoreserver/appstore/locale/en/LC_MESSAGES

6 done

Leave a Comment

Your email address will not be published. Required fields are marked *