我需要从views.py获取请求参数,并使用request.LANGUAGE_CODE将模型对象转换为活动语言,因为现在我正在获取'字符串'对象是默认语言,而不是活动的。我应该如何继续,以便将 init 函数中的参数传递给表单小部件?
来自views.py:
form = ContactForm(lang=request.LANGUAGE_CODE)
forms.py:
from django import forms
from phonenumber_field.formfields import PhoneNumberField
from django.utils.translation import ugettext_lazy as _
from django.utils import translation
from .models import *
strings = Strings.objects.language().get(pk=1)
class ContactForm(forms.Form):
phone = PhoneNumberField(
min_length=9,
max_length=20,
widget=forms.TextInput(attrs={
'id': 'phone-number',
'placeholder': strings.placeholder,
})
)
def __init__(self, *args, **kwargs):
self.lang = kwargs.pop('lang', None)
super(ContactForm, self).__init__(*args, **kwargs)
答案 0 :(得分:1)
试试这段代码:
def __init__(self, *args, **kwargs):
self.lang = kwargs.pop('lang', None)
super(ContactForm, self).__init__(*args, **kwargs)
form.fields['phone'].widget.attrs['placeholder'] = strings.placeholder[self.lang]
当然,您应该实现strings.placeholder[self.lang]
部分(这只是一个示例)来按语言代码本地化您的字符串。
希望这有帮助。