1.在setting.py文件中进行相关设置
1.MIDDLEWARE设置,在SessionMiddleware之后添加:
'django.middleware.locale.LocaleMiddleware'
2.
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
3.
LANGUAGES = (
('en-us', 'English'),
('zh-hans', '中文简体'),
('zh-hant', '中文繁體'),
)
4.
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
2.manage.py 同级目录下新建 locale目录 用于保存翻译消息文件(.po和.mo格式的)
3.生成.po
python manage.py makemessages -l en_us
python manage.py makemessages -l zh_hans
python manage.py makemessages -l zh_hant
注意在setting中是-,但生成文件的时候用_
4.生成mo文件
python manage.py compilemessages
5.引用案例
from django.http import HttpResponse
from django.utils.translation import gettext as _
def index(request):
return HttpResponse(_("text"))
6.设置路由
from django.urls import path
from lang.views import index
from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
path('', index)
)
7.效果
windows系统下使用makemessages和compilemessages命令时会出现错误,这是因为windows缺少基于GNU的gettext模块。
https://mlocati.github.io/articles/gettext-iconv-windows.html下载相应版本,安装或解压缩到C盘或D盘, 比如C:\Program Files (x86)\gettext