Monthly Archives: April 2016

Django国际化

本文在django 1.7验证过

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


+ LOCALE_PATHS = (BASE_DIR+ "/locale",)

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',

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

{% load i18n %}


  • {% trans 'User' %}
  • 3 建立locale目录结构

    $ mkdir locale/en -p
    $ mkdir locale/zh_CN -p
    $ python manage.py makemessages -a
    processing locale zh_CN
    processing locale en

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

    #, fuzzy
    msgid ""
    msgstr ""
    "Project-Id-Version: PACKAGE VERSION\n"
    "Report-Msgid-Bugs-To: \n"
    "POT-Creation-Date: 2016-04-07 10:33+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"

    #: templates/base.html:138
    msgid "User"
    msgstr ""

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

    #: templates/base.html:138
    msgid "User"
    msgstr ""

    5 编译:
    $ python manage.py compilemessages
    processing file django.po in /usr/src/appstoreserver/appstore/locale/zh_CN/LC_MESSAGES
    processing file django.po in /usr/src/appstoreserver/appstore/locale/en/LC_MESSAGES

    6 done