forms.py
class PhoneinfoForm(forms.ModelForm):
pname = forms.CharField(required=True)
pnumber = forms.IntegerField(required=True)
gname = forms.CharField(required=False)
gnumber = forms.IntegerField(required=False)
class Meta:
model = Phone_info
fields = ['pname','pnumber','gname','gnumber']
def clean(self):
cleaned_data = self.cleaned_data
pname = cleaned_data.get("pname")
pnumber = cleaned_data.get("pnumber")
gname = cleaned_data.get("gname")
gnumber = cleaned_data.get("gnumber")
if 'pname' and 'pnumber' not in cleaned_data:
raise forms.ValidationError
if 'gname' and 'gnumber' not in cleaned_data:
raise forms.ValidationError
return cleaned_data
我正在尝试验证姓名和号码。在我的情况下,pname
和pnumber
是一组必填字段,我实现了我的捐赠required=True
。
第二件事是gname
而gnumber
不是强制性的,但是如果输入gnumber
,那么gname
空白(如果没有输入任何名称,则表示接受)这不应该发生。如果输入了数字,则不应在没有名称的情况下接受,反之亦然。
我的代码不适合第二种选择,如何验证这一点。
由于
答案 0 :(得分:1)
您的代码中有几件坏事:
1)当使用forms.ModelForm
时,如果相应的模型字段具有相同的约束,则不需要在表单中声明字段。在问题示例中,如果在模型Phone_info
中相应的字段与表单blank
具有相同的required
属性,则不需要在模型表单中再次声明字段。
2)由于需要pname
和pnumber
,您无需手动检查它们是否已填充。它已由ModelForm
完成。所以这很奇怪,必须删除:
if 'pname' and 'pnumber' not in cleaned_data:
raise forms.ValidationError
3)此行将不执行预期的操作:
if 'gname' and 'gnumber' not in cleaned_data
首先检查条件'gnumber' not in cleaned_data
。结果将是布尔值(True / False)。然后将应用条件if 'gname' and False/True
。
你想要的是:
gname = self.cleaned_data.get("gname", None)
gnumber = self.cleaned_data.get("gnumber", None)
if gname and gnumber is None:
raise forms.ValidationError("gnumber must be filled")
if gnumber is not None and not gname:
raise forms.ValidationError("gname must be filled")
4)正如你在第3页中提到的那样,forms.ValidationError
必须在被提升时被初始化:
raise forms.ValidationError("Error message")
结果代码:
class PhoneinfoForm(forms.ModelForm):
# delete these fields, if they are the same, as in Phone_info
pname = forms.CharField(required=True)
pnumber = forms.IntegerField(required=True)
gname = forms.CharField(required=False)
gnumber = forms.IntegerField(required=False)
class Meta:
model = Phone_info
fields = ['pname', 'pnumber', 'gname', 'gnumber']
def clean(self):
gname = self.cleaned_data.get("gname", None)
gnumber = self.cleaned_data.get("gnumber", None)
if gname and gnumber is None:
raise forms.ValidationError("gnumber must be filled")
if gnumber is not None and not gname:
raise forms.ValidationError("gname must be filled")
return self.cleaned_data