MIDDLEWARE = [
......
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # 此行重点
'django.middleware.common.CommonMiddleware',
......
]
locale
# 国际化翻译文件目录
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'), # 翻译文件所在目录,请手动创建目录
]
python manage.py makemessages -l zh_Hans
python manage.py makemessages -l en
如果上述报错:Can’t find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed
则需要安装 gettext,访问https://mlocati.github.io/articles/gettext-iconv-windows.html 下载安装包,一路next即可
_
函数# 导入
from django.utils.translation import gettext_lazy as _
_("你好") # 纯字符串
_('Today is %(month)s %(day)s.') % {'month': m, 'day': d} # 携带变量的字符串
python manage.py makemessages
# 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 <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-12-18 10:51+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#: .\apps\pvmi_defects\views.py:91
msgid "你好" # 标记的字符串
msgstr "hello" # 对应语言需要显示的字符串
msgid "Today is %(month)s %(day)s." # %(params_name)s 为申明变量
msgstr "今天是%(month)s月%(day)s日"
python manage.py compilemessages
activate
函数from django.utils.translation import activate
from django.utils.translation import activate, get_language_info
from django.utils.translation import gettext_lazy as _
activate("en")
print(_("你好")) # hello
activate("zh-Hans")
print(_("你好")) # 你好
m = 1
d = 2
print(_('Today is %(month)s %(day)s.') % {'month': m, 'day': d}) # 今天是1月2日