如何在Django中翻译表单标签?我试图使用ugettext_lazy,但没有效果。所有网站内容都以正确的方式进行翻译,但表格不是。
用户应该能够手动更改语言,因此我编写了LocaleMiddleware:
class LocaleMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
if (request.user.is_authenticated):
try:
translation.activate(request.user.data.language)
request.LANGUAGE_CODE = request.user.data.language
except:
translation.activate(settings.LANGUAGE_CODE)
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
translation.deactivate()
return response
但表格仍然是默认语言。
表单示例:
class DiscussionCreateForm(forms.Form):
title = forms.CharField(widget=forms.TextInput(attrs={"name": "title", "id": "title", "class": "form-control"}), label=_("title").title())
first_message = forms.CharField(widget=forms.Textarea(attrs={"name": "first_message", "id": "message", "class": "form-control"}), label=_("message").title())
中间件清单:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'PortalCore.middleware.LocaleMiddleware.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'PortalCore.middleware.OnlineMiddleware.OnlineMiddleware',
]
答案 0 :(得分:1)
为什么你在标签中使用。title()
。你应该使用title()
来表示动态字符串而不是静态字符串。
您可以使用大写字符串定义标签,因为您正在使用标题字符串的Capital第一个字符。所以直接在标签中定义。如果你在变量中有字符串,那么title()是可用的。
label=_('Title')
同样也在消息字符串中