How to make email field unique in model User from contrib.auth in Django

后端 未结 19 2127
夕颜
夕颜 2020-11-27 11:47

I need to patch the standard User model of contrib.auth by ensuring the email field entry is unique:

User._meta.fields[4].unique = True
<         


        
19条回答
  •  一个人的身影
    2020-11-27 12:02

    To ensure a User, no matter where, be saved with a unique email, add this to your models:

    @receiver(pre_save, sender=User)
    def User_pre_save(sender, **kwargs):
        email = kwargs['instance'].email
        username = kwargs['instance'].username
    
        if not email: raise ValidationError("email required")
        if sender.objects.filter(email=email).exclude(username=username).count(): raise ValidationError("email needs to be unique")
    

    Note that this ensures non-blank email too. However, this doesn't do forms validation as would be appropriated, just raises an exception.

提交回复
热议问题