在Django中使用多语言(i18n)

在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日
相关推荐
FYKJ_201019 小时前
springboot高考志愿填报推荐系统14332-计算机课程设计、毕业设计
javascript·spring boot·python·架构·django·课程设计·高考
我的xiaodoujiao20 小时前
Django 权限系统项目实战详细图文教程 3--系统登录功能实现
后端·python·django
我的xiaodoujiao1 天前
Django 权限系统项目实战详细图文教程 4--系统登录功能实现 2
后端·python·django
2501_944521591 天前
Immer 跨端三方库仓颉适配全流程
python·eclipse·django
2501_948122632 天前
Qs 跨端三方库仓颉适配全流程
python·react native·django·tornado
CS创新实验室2 天前
改了模型,数据库为什么能自动跟上?——Django 迁移(migrations)的底层
数据库·django·sqlite
weixin_BYSJ19873 天前
电竞先锋网站---附源码02032
java·vue.js·spring boot·python·django·tomcat·php
2601_949847753 天前
Cookie 跨端三方库仓颉适配全流程
python·django·flask
ycydynq5 天前
django利用不涉及数据库form自定义表单 表单元素验证
数据库·django·sqlite
专业程序开发源6 天前
springboot欧缇蔓月子中心管理系统82697-计算机课程设计、毕业设计
java·spring boot·后端·python·spring·django·课程设计