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

后端 未结 19 1895
夕颜
夕颜 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.

    0 讨论(0)
  • 2020-11-27 12:02

    One possible way to do this is to have a pre-save hook on the User object and reject the save of the email already exists in the table.

    0 讨论(0)
  • 2020-11-27 12:04

    In settings module:

    # Fix: username length is too small,email must be unique
    from django.contrib.auth.models import User, models
    User._meta.local_fields[1].__dict__['max_length'] = 75
    User._meta.local_fields[4].__dict__['_unique'] = True
    
    0 讨论(0)
  • 2020-11-27 12:08

    Add somewhere this:

    User._meta.get_field_by_name('email')[0]._unique = True     
    

    and then execute SQL similar to this:

    ALTER TABLE auth_user ADD UNIQUE (email);
    
    0 讨论(0)
  • 2020-11-27 12:09

    What about using unique_together in a "different" way? So far it works for me.

    class User(AbstractUser):
        ...
        class Meta(object):
            unique_together = ('email',)
    
    0 讨论(0)
  • 2020-11-27 12:09

    Simply use below code in models.py of any app

    from django.contrib.auth.models import User
    User._meta.get_field('email')._unique = True
    
    0 讨论(0)
提交回复
热议问题