2012-05-15 107 views
0

我有一個很大的窗體,有兩種可能性。它是事件的一種形式,可以從組合框(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', 
     ) 

回答

0

我結束了使用只是一個普通的形式(不的ModelForm),並根據複選框的狀態clean(self)自定義的驗證,我認爲這是正確的道路要走。然後與self._errors["address"]=ErrorList([u'Some custom error'])我能夠完全自定義驗證過程中可能出現的各種錯誤。

+0

你是如何得到它提交給數據庫的,因爲如果你使用普通形式,對象不會繼承建模保存方法。 – pitchblack408

1

您可以查看clean方法中是否存在表單字段。如果存在,請在其上運行您的自定義驗證規則。

def clean(self): 
    cleaned_data = self.cleaned_data 
    field_name = cleaned_data.get('FIELD_NAME', None) 

    if field_name: 
    ... # do stuff 
    return cleaned_data