在Django中使用多语言
配置中间件
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 manag服务器托管网e.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 , YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSIONn"
"Report-Msgid-Bugs-To: n"
"POT-C服务器托管网reation-Date: 2023-12-18 10:51+0800n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONEn"
"Last-Translator: FULL NAME n"
"Language-Team: LANGUAGE n"
"Language: n"
"MIME-Version: 1.0n"
"Content-Type: text/plain; charset=UTF-8n"
"Content-Transfer-Encoding: 8bitn"
"Plural-Forms: nplurals=1; plural=0;n"
#: .appspvmi_defectsviews.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日
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net