2012-12-04 3 views
0

저는 Ubuntu 12.10에서 Django 1.4와 Python 2.7을 사용하고 있습니다.Django의 동적 선택 필드 유효성 확인

나는 몇 개의 드롭 다운을 동적으로 (jQuery를 사용하여) 채울 필요가 있지만 2 개가 필요하고 3 번째는 선택 사항 인 양식이 있습니다.

API를 사용하여 옵션을 얻으려면 Tastypie를 사용하고 있습니다. 기본적으로 첫 번째 드롭 다운에는 학교의 업계 수준 코드가 입력됩니다. 코드를 선택하면 해당 코드의 모든 범주에 대해 범주 드롭 다운이 채워집니다. 카테고리가 선택되면 해당 카테고리와 카테고리의 조합에 대한 모든 하위 카테고리에 대해 하위 카테고리 드롭 다운이 채워집니다.

코드 드롭 다운을 요구할 수 있습니다 (동적으로 채워지지는 않음). 그러나 카테고리 드롭 다운이 필요할 때가 점점 어려워지고 있습니다. 기본적으로 프론트 엔드 유효성 검사 또는 백 엔드 유효성 검사라는 두 가지 경로가 있습니다. 백엔드 유효성 검사를 수행하려고하므로 필요에 따라 추가 유효성 검사를 쉽게 만들 수 있습니다. 나는 clean 메서드를 재정의하려고했습니다

class SchoolProductForm(forms.ModelForm): 
    cip_category = forms.ChoiceField(required=True, 
            choices=(('', '----------'),)) 

    def __init__(self, *args, **kwargs): 
     super(SchoolProductForm, self).__init__(*args, **kwargs) 

     self.fields['short_description'].widget = TA_WIDGET 
     self.fields['salary_info'].widget = TA_WIDGET 
     self.fields['job_opportunities'].widget = TA_WIDGET 
     self.fields['related_careers'].widget = TA_WIDGET 
     self.fields['meta_keywords'].widget = TI_WIDGET 
     self.fields['meta_description'].widget = TI_WIDGET 
     self.fields['cip'].queryset = models.CIP.objects.filter(
      parent_id__isnull=True) 


    class Meta: 
     model = models.SchoolProduct 
     exclude = ('campus',) 

: 여기

는 형태입니다. 필드를 특정 clean 메서드를 만들려고했습니다. 어느 쪽도 효과가없는 것 같습니다. 다음의

변화는 :

def clean(self): 
    super(SchoolProductForm, self).clean() 
    if cip_category in self._errors: 
     del self._errors['cip_category'] 
    if self.cleaned_data['cip_category'] == '----------': 
     self._errors['cip_category'] = 'This field is required.' 

    return self.cleaned_data 

이 그것을 확인하지 않았기 때문에 의미가 cleaned_data에는 cip_category가 없다는 오류를 제공합니다.

I 필드 특정 깨끗하고 변화를 시도했다 :

def clean_cip_category(self): 
    data = self.cleaned_data['cip_category'] 
    self.fields['cip_category'].choices = data 

    return data 

을하지만 내 선택을 알리는 페이지에서 유효성 검사 오류는 가능한 선택 중 하나가 아닙니다.

나는 동적 필드 유형 (몇 가지 변화) 만들려고했습니다

class DynamicChoiceField(forms.ChoiceField): 
    def valid_value(self, value): 
     return True 

class SchoolProductForm(forms.ModelForm): 
    cip_category = DynamicChoiceField(required=True, 
             choices=(('', '----------'),)) 

을하지만 유효한 옵션으로 ----------을 받아 (내가 원하지 않는)와 ORM의 시도하기 때문에 오류가 발생합니다 데이터베이스에있는 ---------- 값과 일치해야합니다 (찾을 수 없음).

아이디어가 있으십니까?

답변

1

ChoiceField의 방법을 약간 무시하여이 문제를 해결할 수있었습니다.

나는 폼에 필드를 추가하고 self.initial와 사전 인구 처리 :보기에 나는 form_valid에서 처리 추가

class DynamicChoiceField(forms.ChoiceField): 
    def valid_value(self, value): 
     return True 

다음 :

class SchoolProductForm(forms.ModelForm): 
    cip_category = common_forms.DynamicChoiceField(
     required=True, choices=(('', '----------'),)) 

    def __init__(self, *args, **kwargs): 
     super(SchoolProductForm, self).__init__(*args, **kwargs) 

     self.fields['short_description'].widget = TA_WIDGET 
     self.fields['salary_info'].widget = TA_WIDGET 
     self.fields['job_opportunities'].widget = TA_WIDGET 
     self.fields['related_careers'].widget = TA_WIDGET 
     self.fields['meta_keywords'].widget = TI_WIDGET 
     self.fields['meta_description'].widget = TI_WIDGET 
     self.fields['cip'].queryset = models.CIP.objects.filter(
      parent_id__isnull=True) 

     # Get the top parent and pre-populate 
     if 'cip' in self.initial: 
      self.initial['cip'] = models.CIP.objects.get(
       pk=self.initial['cip']).top_parent() 

    class Meta: 
     model = models.SchoolProduct 
     exclude = ('campus',) 

DynamicChoiceField입니다 재정의 :

def form_valid(self, form): 
    self.object = form.save(commit=False) 

    # Handle the CIP code 
    self.object.cip_id = self.request.POST.get('cip_subcategory') 
    if self.object.cip_id == '': 
     self.object.cip_id = self.request.POST.get('cip_category') 

    self.object.save()