![](https://img-blog.csdnimg.cn/img_convert/f3a591ab19bc23eb9407d6f35c9483d8.png)
1. 在python代码中嵌入
//settings.py
LANGUAGES = (
('zh-hans', gettext_lazy('Simplified Chinese')),
)
然后注意了要在locale的文件夹下执行命令行
django-admin makemessages -l zh_Hans
![](https://img-blog.csdnimg.cn/img_convert/94426c4c79277f1c71f00453cf48f578.png)
![](https://img-blog.csdnimg.cn/img_convert/a8472473071b90c6a73614334158679e.png)
然后编译一下
django-admin compilemessages
![](https://img-blog.csdnimg.cn/img_convert/9ce903fd8ebac6ce3e5d7499337be807.png)
编写views.py以及配置settings.py
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.translation import gettext_lazy as _
# Create your views here.
def index(request):
tmp=_("Hello world!")
return HttpResponse(tmp)
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
![](https://img-blog.csdnimg.cn/img_convert/80fa3893e837a0498002d0e6fdb70678.png)
LANGUAGES = (
('zh-hans', gettext_lazy('Simplified Chinese')),
('en-us',gettext_lazy('English')),
)
python manage.py migrate
python manage.py runserver
![](https://img-blog.csdnimg.cn/img_convert/24b2ec5d0573ba8ada7f4f273cece646.png)
![](https://img-blog.csdnimg.cn/img_convert/b8ddd02d9c59299ab89a8b990c993911.png)
![](https://img-blog.csdnimg.cn/img_convert/3e26df000da5949e01ab5394a1210089.png)
2. 在模板中嵌入
首先编写html文件
<!DOCTYPE html>
<html lang="en">
<head>
{% load i18n %}
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<p>{% blocktrans %} {{ person }} say hello {% endblocktrans %}</p>
</body>
</html>
同上建立locale文件夹,在app文件夹下
![](https://img-blog.csdnimg.cn/img_convert/eb0311046324de8d6e0429bb6d1c06a2.png)
然后在locale文件夹下修改这个文件
![](https://img-blog.csdnimg.cn/img_convert/1b4a746c75f3c597de2d62b4ac2ef290.png)
![](https://img-blog.csdnimg.cn/img_convert/4c23547924cdffdfe7f8aec6744e4f78.png)
然后编译一下
django-admin compilemessages
![](https://img-blog.csdnimg.cn/img_convert/7d1f43563de174dae21a38e6067b339b.png)
然后编写views.py把模板导入
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.utils.translation import gettext_lazy as _
# Create your views here.
def index(request):
tmp=_("Hello world!")
return HttpResponse(tmp)
def test(request):
t=loader.get_template('test.html')
return HttpResponse(t.render({
'person':'tony'
}))
最后编写一下urls.py就可以了,实验结果如下:
![](https://img-blog.csdnimg.cn/img_convert/5dcf2753e30651263d5db83f501d3cc0.png)
![](https://img-blog.csdnimg.cn/img_convert/43765ec66cd73865dc7007997dbfbcdb.png)