正经的官网链接:https://docs.djangoproject.com/zh-hans/3.0/topics/i18n/translation/
settings.py
配置
MIDDLEWARE = [
'...',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # 添加中间件
'django.middleware.common.CommonMiddleware',
'...',
]
TEMPLATES = [
{
'OPTIONS': {
'context_processors': [
'...',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.i18n', # 添加模板上下文
],
},
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = (
('en-us', ('English')),
('zh-hans', ('简体中文')), # 这里的 zh-hans 是小写
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'), # 把翻译文件单独放到项目目录 locale 下
)
生成翻译文件 .po
python manage.py makemessages -l zh_Hans # 注意大小写,不是 zh_hans,这点很坑
编译生成 .mo
python manage.py compilemessages
常见问题
CommandError: Can’t find msguniq
CommandError: Can’t find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.
GNU gettext 官网:http://www.gnu.org/software/gettext/
Windows 下载地址:https://mlocati.github.io/articles/gettext-iconv-windows.html
Ubuntu安装gettext:apt install gettext