1 回答
TA贡献1993条经验 获得超6个赞
您可以覆盖模型的clean()方法。作为参考,通过 保存模型实例ORM不会调用模型的clean()方法。
所以当你子类化时AbstractUser:
from django.core.exceptions import ValidationError
class User(AbstractUser):
def clean(self):
super().clean()
if not self.first_name and not self.last_name:
raise ValidationError({
'first_name': ValidationError('Please set this', code='error1'),
'last_name': ValidationError('... or this', code='error2')
})
不要忘记Django按照文档中的描述配置您的项目。您还需要确保使用此模型的表单始终实现字段first_name和last_name,否则您将获得ValueError.
因此,每次将 aModelForm与User模型结合使用时clean()都会被调用。如在Django的UserChangeForm,UserCreationForm等等。
添加回答
举报
