1. 安装gettext
2. 在项目主目录下创建locale文件夹
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
3. 生成需要的语言
python manage.py makemessages -l zh_Hans
python manage.py makemessages -l jp
4. 在视图中选择要使用的语言
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.utils import translation
# Create your views here.
def about_us(request):
language = request.GET.get('language', 'en')
translation.activate(language)
output = _('hello world')
return HttpResponse(output)
def index(request):
language = request.GET.get('language', 'en')
translation.activate(language)
return render(request, 'index.html', {})
5. 在django.mo文件中的msgstr ""中添加翻译后的文字
6. 编译
python manage.py compilemessages