Django应用的本地化仅适用于forms.py而不适用于models.py
我在本地化我的应用程序时遇到了问题。这个应用程序支持两种语言:英语和德语。问题出现在浏览器语言设置为英语(美国),而我的设置文件却是设置为“de”(德语),反之亦然。在这种情况下,有些字段显示为英语,有些则显示为德语。我的模型中包含了字符字段(CharField)、小数字段(DecimalField)和日期字段(DateField)。
models.py:
from django.db import models
from django.utils.translation import ugettext as _
class Test(models.Model):
test_number = models.CharField(_('Test number'), max_length=20)
test_date = models.DateField()
test_price = models.DecimalField(_('Test price'), max_digits=16, decimal_places=2, null=True, blank=True)
forms.py:
class TestForm(ModelForm):
test_date = forms.DateField(label=_('Booking date'), widget=AdminDateWidget)
settings.py
USE_L10N = True
USE_I18N = True
TIME_ZONE = 'Europe/Berlin'
LANGUAGE_CODE = 'de'
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
'django.middleware.transaction.TransactionMiddleware',
'pagination.middleware.PaginationMiddleware',
)
浏览器设置为英语。在这种情况下,字段 test_number 和 test_price 的标签显示为德语,而 test_date 的标签则是英语。如果我把 models.py 中的 _('Test number') 去掉,然后在 forms.py 中作为标签属性添加,它就能正常工作。难道没有其他方法可以做到这一点吗?
2 个回答
0
仔细检查一下你的 .po
文件:里面不应该有任何标记为“模糊”的状态。
2
把声明“from django.utils.translation import ugettext as _”改成“from django.utils.translation import ugettext_lazy as _”似乎能解决这个问题。