我尝试了django rest框架的国际化。
doc drf国际化
从www.example.com中的官方drf文档获取一组此代码settings.py
from django.utils.translation import gettext_lazy as _
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
]
LANGUAGE_CODE = "it"
LANGUAGES = (
('en', _('English')),
('it', _('Italian')),
('fr', _('French')),
('es', _('Spanish')),
)
TIME_ZONE = 'UTC'
USE_I18N = True
但是当我试用POST API时
curl -X 'POST' \
'http://172.18.0.1:7000/appjud/api/v1/reset-password/' \
-H 'accept: application/json' \
-H 'Authorization: Token 014cb7982f31767a8ce07c9f216653d4674baeaf' \
-H 'Content-Type: application/json' \
-d '{
"new_password": "",
"confirm_password": ""
}'
Response body
[
{
"newpassword": [
"This field is required."
],
"confirmpassword": [
"This field is required."
]
}
]
Response headers
allow: POST,OPTIONS
content-language: en
content-length: 91
content-type: application/json
cross-origin-opener-policy: same-origin
date: Sat,03 Dec 2022 16:14:16 GMT
referrer-policy: same-origin
server: WSGIServer/0.2 CPython/3.9.15
vary: Accept,Accept-Language,Origin
x-content-type-options: nosniff
x-frame-options: DENY
更新
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
正如我们可以看到它打印“This field is required.”但我想“Questo campo è obbligatorio.”我在配置www.example.com文件中错过了什么settings.py?
1条答案
按热度按时间6vl6ewon1#
看起来您将
LocaleMiddleware
添加到了中间件列表的末尾。但这里的顺序很重要。来自文档:由于中间件顺序很重要,因此请遵循以下准则:
确保它是最先安装的中间件之一。它应该在SessionMiddleware之后,因为LocaleMiddleware使用会话数据。它应该在CommonMiddleware之前,因为CommonMiddleware需要激活的语言才能解析请求的URL。如果使用CacheMiddleware,请将LocaleMiddleware放在它之后。
试着根据这张纸条改变顺序。