当我的“参考”字段与“联系人”相同时,我试图引发验证错误,但是
def clean
不起作用。
这是我的代码:
class FacultyRegistration(models.Model):
role = models.ForeignKey(Roles, on_delete=models.CASCADE, null=True, verbose_name="Faculty Role")
contact = models.OneToOneField('Contacts.Contact', related_name='faculty_Contact', unique=True,
on_delete=models.CASCADE)
reference = models.ForeignKey('Contacts.Contact', on_delete=models.CASCADE, related_name='faculty_reference',)
# I tried def clean but it wont work
def clean(self):
if self.contact == self.reference:
raise ValidationError('Primary and secondary inclinations should be different.')
def __str__(self):
return f"{self.contact} ({self.role})"
class Meta:
verbose_name = "Faculty Management"
verbose_name_plural = "Faculty Managements"
您可以使用 forms.py 中的表单来完成此操作:
class FacultyRegistrationForm(forms.ModelForm):
class Meta:
model = FacultyRegistration
fields = '__all__'
def _post_clean(self):
contact = self.cleaned_data.get('contact')
reference = self.cleaned_data.get('reference')
if contact == reference :
self.add_error("reference", "Primary and secondary inclinations should be different.")
在 django/forms/forms.py 中可以看到 _post_clean 是一个内部钩子,用于在表单清理完成后执行额外的清理。
您将阅读源代码: full_clean方法运行:
self._clean_fields()
self._clean_form()
self._post_clean()
clean 方法是一个钩子,用于在 field.clean() 之后进行任何额外的表单范围清理。清理后方法在表单清理后运行。