在Django中使用多语言
配置中间件
python
MIDDLEWARE = [
......
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # 此行重点
'django.middleware.common.CommonMiddleware',
......
]
配置翻译文件目录
- 根目录下创建目录
locale
python
# 国际化翻译文件目录
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'), # 翻译文件所在目录,请手动创建目录
]
创建语言文件
python
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
python manage.py makemessages
文件内容如下
python
# 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
python manage.py compilemessages
如果需要动态切换语言,可以使用activate
函数
python
from django.utils.translation import activate
示例
python
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日