[英]django rest framework translation does not work for me
I tried django rest framework internationalization.我尝试了 django rest 框架国际化。
doc drf internationalization 文档drf国际化
From official drf documentation a set this code in settings.py从官方 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
but when I try out POST api rest但是当我尝试 POST api rest
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
UPDATE更新
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
As we can see it print "This field is required."正如我们所看到的,它会打印“此字段为必填项”。 but I would like "Questo campo è obbligatorio."但我想要“Questo campo è obbligatorio”。 What Does I miss in config settings.py file?我在配置 settings.py 文件中遗漏了什么?
Looks like you added LocaleMiddleware
to the end of middlewares list.看起来您已将LocaleMiddleware
添加到中间件列表的末尾。 But order is matter here.但秩序在这里很重要。 From the docs :从文档:
Because middleware order matters, follow these guidelines:由于中间件顺序很重要,请遵循以下准则:
Make sure it's one of the first middleware installed.确保它是最先安装的中间件之一。 It should come after SessionMiddleware, because LocaleMiddleware makes use of session data.它应该在 SessionMiddleware 之后,因为 LocaleMiddleware 使用 session 数据。 And it should come before CommonMiddleware because CommonMiddleware needs an activated language in order to resolve the requested URL. If you use CacheMiddleware, put LocaleMiddleware after it.它应该出现在 CommonMiddleware 之前,因为 CommonMiddleware 需要一种激活的语言才能解析请求的 URL。如果您使用 CacheMiddleware,请将 LocaleMiddleware 放在它之后。
Try to change order according to this note.尝试根据此说明更改顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.