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