2017-06-11 91 views
1

當我嘗試驗證Django表單時,如果選擇「其他狀態」(美國境外的狀態),用戶必須在另一個表單上鍵入狀態字段(其他州字段)。如果他的州是美國州,則不需要其他州的州。 以下是我的代碼;驗證django中的其他狀態表單字段

models.py

class User(models.Model): 
    First_Name = models.CharField(max_length=100) 
    Last_Name = models.CharField(max_length=100) 
    Date_of_Birth = models.DateField() 
    State_of_Origin = models.CharField(max_length=50, choices=STATE_CHOICES) 
    Other_State = models.CharField(max_length=50, null=True) 
    Marita_status = models.CharField(max_length=50, choices=STATUS_CHOICES) 
    Country = CountryField(default='US') 
    Email = models.EmailField(unique=True) 
    Phone_Number = PhoneNumberField("Phone Number(+1..)", default='+1') 

Form.py

class RegForm(forms.ModelForm): 
    Date_of_Birth = forms.DateField(widget=AdminDateWidget()) 
    #Other_State = forms.CharField(max_length=50, required=False) 

    class Meta(): 
     model = User 
     fields = '__all__' 

    def clean_State_of_Origin(self): 
     State_of_Origin = self.cleaned_data['State_of_Origin'] 
     return State_of_Origin 

    def clean_Other_State(self): 
     Other_State = self.cleaned_data['Other_State'] 
     if Other_State != 'Other': 

      self.Other_State = forms.CharField(max_length=50, required=False) 
     else: 
      raise forms.ValidationError("Name is invalid") 

回答

0
def clean(self): 
     Other_State = self.cleaned_data['Other_State'] 
     State_of_Origin = self.cleaned_data['State_of_Origin'] 
     if State_of_Origin == 'Other': 
      if not Other_State: 
       raise forms.ValidationError('Write Other State name because you selected other option from state of origin dropdown') 
     return Other_State 
+0

感謝NeErAj庫馬爾,你的解決方案工作。我不得不從你的代碼中刪除「return Other_State」,因爲我得到'str'對象沒有屬性'get'錯誤。 – gnome247

0

當驗證領域對對方你需要使用清潔方法。像這樣的東西:

class RegForm(forms.ModelForm): 
    Date_of_Birth = forms.DateField(widget=AdminDateWidget()) 
    Other_State = forms.CharField(max_length=50, required=False) 

    class Meta(): 
     model = User 
     fields = '__all__' 

    def clean(self): 
     Other_State = self.cleaned_data['Other_State'] 
     if Other_State != 'Other': 
      self.add_error('Other_State', "Name is invalid") 

這樣的事情應該讓你開始。

另外,嘗試使用pep8變量名稱。 DATE_OF_BIRTH代替DATE_OF_BIRTH