简体   繁体   English

如果电子邮件存在,如何在 Django 模型中引发 ValidationError

[英]How to raise ValidationError in Django model if email exist

I am trying to raise ValidationError through validators.py or def clean(self) on an email field in the Django model to know if an email exists in the DB.我正在尝试通过 Django 模型中的电子邮件字段上的validators.pydef clean(self)引发 ValidationError 以了解数据库中是否存在电子邮件。

Below is a brief of my model:以下是我的模型简介:

class Profile(models.Model)
   ...
   email = models.EmailField()
   ...

   def __str__(self)
       return self.f_name

I know I can add unique=True to the model field to ensure that, or simply do a cleaned_data in forms, but the solution I want is that of validator.py or def clean(self) in models.py .我知道我可以在模型字段中添加unique=True以确保,或者只是在表单中做一个cleaned_data ,但我想要的解决方案是在models.py中使用validator.pydef clean(self)

For future reference, if anyone comes across the same issue, all thanks to @dirkgroten, I was able to resolve the problem with clean() in my models.py :为了将来参考,如果有人遇到同样的问题,这一切都归功于@dirkgroten,我能够在我的models.py使用clean()解决问题:

def clean(self)
     if Profile.objects.filter(email=self.email).exclude(pk=self.pk).exists():
            raise ValidationError({'email': _('Email already exists.')})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM