我正在尝试使用Django显示一个表单,但是如果用户语言是' en'我想删除一个字段。我想避免在Javascript中执行此操作或仅为此执行第二个模板。所以我想知道是否可以将参数传递给我Meta()
类的UserForm()
类。这样我就可以通过用户并用if
语句检查他的语言。
这是我到目前为止所做的:
class UserForm(forms.ModelForm):
first_name = forms.CharField(required=True, label=_('*First name'))
last_name = forms.CharField(required=True, label=_('*Last name'))
postal_code = FRZipCodeField(required=False, label=_('My postcode'))
birthday = forms.DateField(
widget=forms.DateInput(format='%d/%m/%Y'),
required=False,
input_formats=['%d/%m/%Y'],
label=_('My birthday'))
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Field('gender'),
Field('first_name'),
Field('last_name'),
Field('birthday'),
Field('country'),
Field('language'),
Field('payment_preference'),
Div('addr1', css_class='hidden', css_id='addr1_container'),
Div('addr2', css_class='hidden', css_id='addr2_container'),
Div('addr3', css_class='hidden', css_id='addr3_container'),
Div('postal_code', css_class='hidden', css_id='pc_container'),
Div('city', css_class='hidden', css_id='city_container'),
ButtonHolder(
Submit('save', _('update'), css_class='pull-right'),
)
)
class Meta():
model = User
fields = (
"first_name", "last_name", "gender", "birthday", "country",
"payment_preference", "addr1", "addr2", "addr3", "postal_code",
"city", "language",)
使用if,我可以在Meta()类中设置两个不同的字段变量,因此为每种用户语言显示两种不同的形式。
答案 0 :(得分:1)
您无法将其传递给Meta,但您可以将其传递到__init__
并隐藏您要隐藏的字段:
class UserForm(forms.ModelForm):
# ... as before
def __init__(self, user, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
if user.language == 'en':
self.fields['field_name'].widget = forms.HiddenInput()
# ... as before
然后,当您调用表单时,将用户作为第一个参数传递:
form = UserForm(request.user, ...)