我有一个由动态字段组成的抽象Form
类:
class AddressForm(forms.Form):
def __init__(self, all_required=True, *args, **kwargs):
super(AddressForm, self).__init__(*args, **kwargs)
self.fields['street_num'] = forms.CharField(max_length=10, label='Street number', required=all_required)
self.fields['street_dir'] = DirectionFormField(required=all_required)
self.fields['street_name'] = forms.CharField(max_length=35, required=all_required)
self.fields['city'] = forms.CharField(max_length=35, required=all_required)
self.fields['state'] = forms.ChoiceField(choices=STATE_ABBREVS, required=all_required)
self.fields['zip'] = ZipCodeFormField(max_length=5, required=all_required)
class Meta:
abstract = True
以下是我使用它的方式:
class AddressCreateForm(AddressForm):
name = forms.CharField(max_length=30)
如果我在视图中的AddressCreateForm
对象上调用is_valid(),我发现它总是返回false。但是,不会返回任何错误。如果AddressForm
类没有如下的动态字段,那么一切正常:
class AddressForm(forms.Form):
street_num = forms.CharField(max_length=10, label='Street number')
street_dir = DirectionFormField()
street_name = forms.CharField(max_length=35)
city = forms.CharField(max_length=35)
state = forms.ChoiceField(choices=STATE_ABBREVS)
zip = ZipCodeFormField(max_length=5)
class Meta:
abstract = True
我在课堂上遗漏了哪些动态字段?
根据Fiver的建议,__init__
应该以此开头:
class AddressForm(forms.Form):
def __init__(self, *args, **kwargs):
if kwargs.get('all_required') == None:
all_required = True
else:
all_required = kwargs['all_required']
kwargs.pop('all_required')
super(AddressForm, self).__init__(*args, **kwargs)
#...
这很有效。