django multi-language internationalization

Introduction

Django internationalization support, multi-language. Django's internationalization is enabled by default, if you do not need international support, you can set USE_I18N = False in your settings file, then Django will make some optimization, do not load international support mechanisms.

NOTE: 18 represents Internationalization letter word among the first letter I and ends with the letter N 18. I18N is Internationalization (international) mean.

Django fully supports translation of text, date, time and time zone digital format.

Essentially, Django does two things:

  1. It allows developers to specify translation strings
  2. Django call the appropriate translated text according to the specific preferences of visitors.

Open support internationalization, we need to set in settings.py file

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.locale.LocaleMiddleware',
)
 
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
 
LANGUAGES = (
    ('en', ('English')),
    ('zh-cn', ('中文简体')),
    ('zh-tw', ('中文繁體')),
)
 
# 翻译文件所在目录,需要手工创建
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
 
TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "django.core.context_processors.i18n",
)

Note: Django 1.9 and above, the language of the code changes

LANGUAGES = (
    ('en', ('English')),
    ('zh-hans', ('中文简体')),
    ('zh-hant', ('中文繁體')),
)
# en,zh-hans就是语言的代码

Generate documents to be translated

Will automatically place you want to translate .po files are updated to

Django 1.8 and below versions

python manage.py makemessages -l zh-cn
python manage.py makemessages -l zh-tw

Django 1.9 and above to be changed

python manage.py makemessages -l zh_hans
python manage.py makemessages -l zh_hant

Manual translation locale in django.po

...
 
#: .\tutorial\models.py:23
msgid "created at"  # 要翻译的语句
msgstr "创建于"      # 翻译后的语句
 
#: .\tutorial\models.py:24
msgid "updated at"
msgstr "更新于"
 
...

Compiler that will take effect this translation

python manage.py compilemessages

If the translation does not take effect, please check your language pack folder is not there in the dash, please replace it with an underscore .

For example, zh-hans into zh_hans (but to pay attention to setttings.py underlined in use, do not also changed )

Guess you like

Origin www.cnblogs.com/liuweida/p/12081221.html