2012-05-15 12 views
0

두 가지 가능성이있는 꽤 큰 폼이 있습니다. 이벤트의 양식이며, 콤보 박스 (ModelChoice 쿼리)에서 이벤트 위치를 선택할 수 있습니다. 그러나 사용자가 "새 위치"확인란을 선택한 다음 새 위치를 삽입하는 데 필요한 필드가 양식에 표시되고 "기존 위치"콤보 상자가 재설정됩니다. 자,이 모든 자바 스크립트 (jQuery)와 함께 아주 잘 작동하지만, 내 문제는 어떻게 양식에서 사용되지 않는 필드의 유효성을 검사하는 것입니다.Django ModelForm, 사용자 정의 유효성 확인

간단히 말해서 "다른 위치는"새 위치 "확인란의 상태에 따라 반면, 나는 그 중 하나가 항상 필수 (이벤트 유형, datetime 등) 7 양식 fileds있다 :> new_location가 선택되어 있으면> 위치 등 필드를 확인하고 나머지는 무시 (비워 둠)하고, 나머지는 위치 필드를 무시하고 나머지는 유효성을 검사합니다.

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 
관련 문제