尽管我阅读了文档,但我对 django 表单验证感到非常困惑。
我定义了以下形式:
class NewProjAccount(NewAccount):
def __init__(self, perforce='', *args, **kwargs):
super(NewProjAccount, self).__init__(*args, **kwargs)
print perforce
if 'on' in perforce:
self.fields['perforce_depot_size'].widget.attrs[
'required'] = True
site = forms.ChoiceField(choices=SITE_CHOICES, required=False,
label="Site")
project_name = forms.CharField(max_length=25, required=True,)
disk_usage = forms.IntegerField(max_value=PROJ_MAX_SIZE_GB,
)
homes = forms.MultipleChoiceField(choices=SITE_CHOICES, required=False,
widget=
forms.widgets.CheckboxSelectMultiple(),
label="Remote Homes")
perforce_depot = forms.BooleanField(required=False)
perforce_depot_size = forms.IntegerField(max_value=PERFORCE_MAX_SIZE_GB,
required=False)
class ReviewProjAccount(NewProjAccount):
site = forms.CharField(max_length=20, required=False,
label="Site")
project_name = forms.CharField(max_length=25, required=True,)
homes = forms.CharField(label="Remote Homes")
perforce_depot = forms.BooleanField(required=False,
widget=forms.widgets.CheckboxInput(
attrs={'disabled': 'disabled'}))
两种形式都继承自:
class NewAccount(forms.Form):
"""
Base class for all the account type
"""
def __init__(self, readonly=False, *args, **kwargs):
super(NewAccount, self).__init__(*args, **kwargs)
if readonly:
for field in self.fields.itervalues():
field.widget.attrs['readonly'] = 'readonly'
我的想法是像这样使用这种形式:
if request.method == 'POST':
try:
form = NewProjAccount(perforce=request.POST['perforce_depot'],
data=request.POST)
except MultiValueDictKeyError:
print "caugh"
if request.POST['perforce_depot_size']:
form = ReviewProjAccount(data=initial_val,
readonly=True)
else:
form = NewProjAccount(data=request.POST)
但是,这会导致一个非常复杂的视图函数,其中可能包含“if”和“else”以及“try ... example”...
所以,我的问题是:
有没有一种简单的方法来定义表单中的字段之间的关系,这样当一个是时True
,它会触发另一个字段的验证器?
就我而言,我想当用户选择:
perforce_depot = True
,或者应该将属性'on'
设置为.perforce_depot_size
required
True