当我尝试验证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 :(得分:0)
当验证字段相互对照时,您需要使用clean方法。像这样:
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
答案 1 :(得分: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