0
我遵循Django文档设置国际化。django rest框架如何国际化字段
我需要根据请求的语言返回各种选择字段的翻译。
例如,我有以下选择字段;
CHOICE_TYPES = (('short', _('Short Term')),('long', _('Long Term')), ('mixed', _('Mixed')),)
我已经按照文档设置了我的Locale和.po文件。例如;
msgid "Short Term"
msgstr "단기계약"
我在请求中使用Accept-Language标头请求语言。
但似乎Django没有看到语言环境,或者我还没有为DRF采取另一个步骤。
Django确实看到了语言请求,因为我正在使用django-hvad进行模型翻译,并且它们被正确返回。
任何帮助,将不胜感激。
编辑:添加了相关的代码提取
Settings.py
LANGUAGES = [
('en', _('English')),
('ja', _('Japanese')),
]
LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# replicated locale folder in 3 locations as I thought Django couldn't find it
LOCALE_PATHS = (
'../locale',
'<full_path>locale',
'<full_path>/<app_name>/locale',
)
models.py
from django.utils.translation import ugettext_lazy as _
CHOICES = (('short', _('Short Term')),('long', _('Long Term')), ('mixed', _('Mixed')),)
# In the relevant model/s
term = models.CharField(max_length=10, choices=CHOICES, default='short')
serializers.py
class SomethingSerializer(TranslatableModelSerializer):
class Meta:
depth = 1
model = Something
fields = (...., ...., 'term')
在现场/ JA/LC_MESSAGES
django.po
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"Language: ja\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Translated-Using: django-rosetta 0.7.12\n"
#: common/models.py:8
msgid "Short Term"
msgstr "test translation"
最后我跑的命令如下:
$ ./manage.py makemessages -l ja
processing locale ja
$ ./manage.py compilemessages -l ja
processing file django.po in /<Path>/locale/ja/LC_MESSAGES
processing file django.po in /<Path>/locale/ja/LC_MESSAGES
processing file django.po in /<Path>/<App Name>/locale/ja/LC_MESSAGES
您是否在运行服务器的系统上调用了'python manage.py compilemessages'? – schwobaseggl
您是否可以包含步骤和代码来重现问题? – Marat