这是一个 Django 模型示例:
from django.db import models
from django.core.exceptions import ValidationError
class MyModel(models.Model):
field1 = models.CharField(null=True)
field2 = models.CharField(null=True)
def clean(self):
if self.field1 and self.field2:
raise ValidationError(
'Please select only field1 OR field2, not both.')
elif self.field1 is None and self.field2 is None:
raise ValidationError(
'Please select field1 or field2.')
我想要实现的是强制我的应用程序的管理员从两个可用字段中选择一个且仅一个字段。问题是我的代码很好地阻止了添加选择了两个字段的新对象,但它并不能阻止添加没有选择字段的新对象;第二部分仅在管理员想要编辑既没有
field1
也没有 field2
的对象时才起作用,但可以首先添加它,我希望阻止这种情况。关于如何解决这个问题有什么想法吗?
如果该人没有填写表单字段,它会将其视为空字符串,而不是
None
,因此您应该检查项目的真实性(因此如果字段是None
或,它将匹配)空字符串 ''
):
def clean(self):
if self.field1 and self.field2:
raise ValidationError(
'Please select only field1 OR field2, not both.')
elif self.field1 and self.field2:
raise ValidationError(
'Please select field1 or field2.')
为什么elif中也是同样的情况,应该是这样吗
def clean(self):
if self.field1 and self.field2:
raise ValidationError(
'Please select only field1 OR field2, not both.')
elif not (self.field1 or self.field2):
raise ValidationError(
'Please select field1 or field2.')