我有一个很大的窗体,有两种可能性。它是事件的一种形式,可以从组合框(ModelChoice查询)中挑选事件位置。但是,用户可以选中“新位置”复选框,然后表单显示需要插入新位置的字段,并且“现有位置”组合框被重置。现在,这一切都与JavaScript(jQuery)非常好,但我的问题是如何验证表单中未使用的字段。我有7个表格文件,其中3个总是强制性的(事件类型,日期时间等),而另一个取决于复选框“新位置”的状态:如果new_location被选中>验证位置等字段,并忽略其余(允许它们为空),otherwisw忽略位置字段并验证其余。Django ModelForm,自定义验证
class EventForm(ModelForm):
area = forms.ModelChoiceField(
queryset=Area.objects.order_by('name').all(),
empty_label=u"Please pick an area",
label=u'Area',
error_messages={'required':u'The area is mandatory!'})
type = forms.ModelChoiceField(
queryset=SportType.objects.all(),
empty_label=None,
error_messages={'required':'Please pick a sport type!'},
label=u"Sport")
#shown only if new_location is unchecked - jQuery
location = forms.ModelChoiceField(
queryset=Location.objects.order_by('area').all(),
empty_label=u"Pick a location",
error_messages={'required':'Please pick a location'},
label=u'Location')
#trigger jQuery - hide/show new location field
new_location = forms.BooleanField(
required=False,
label = u'Insert new location?'
)
address = forms.CharField(
label=u'Locatio address',
widget=forms.TextInput(attrs={'size':'30'}),
error_messages={'required': 'The address is required'})
location_description = forms.CharField(
label=u'Brief location description',
widget=forms.Textarea(attrs={'size':'10'}),
error_messages={'required': 'Location description is mandatory'})
class Meta:
model = Event
fields = (
'type',
'new_location',
'area',
'location',
'address',
'location_description',
'description',
)
你是如何得到它提交给数据库的,因为如果你使用普通形式,对象不会继承建模保存方法。 – pitchblack408