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