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

后端 未结 19 1906
夕颜
夕颜 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:09

    Your form should look something like this.

    def clean_email(self):
        email = self.cleaned_data.get('email')
        username = self.cleaned_data.get('username')
        print User.objects.filter(email=email).count()
        if email and User.objects.filter(email=email).count() > 0:
            raise forms.ValidationError(u'This email address is already registered.')
        return email
    
    0 讨论(0)
  • 2020-11-27 12:09

    The first answer here is working for me when I'm creating new users, but it fails when I try to edit a user, since I am excluding the username from the view. Is there a simple edit for this that will make the check independent of the username field?

    I also tried including the username field as a hidden field (since I don't want people to edit it), but that failed too because django was checking for duplicate usernames in the system.

    (sorry this is posted as an answer, but I lack the creds to post it as a comment. Not sure I understand Stackoverflow's logic on that.)

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

    from an User inherited model, redefine the attribute correctly. It should work, as is it's not usefull to have that in django core because it's simple to do.

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

    Since version 1.2 (May 11th, 2015) there has been a way to dynamically import any chosen registration form using the settings option REGISTRATION_FORM.

    So, one could use something like this:

    REGISTRATION_FORM = 'registration.forms.RegistrationFormUniqueEmail'

    This is documented here.

    And here's the link to the changelog entry.

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

    Add the below function in any of the models.py file. Then run makemigrations and migrate. Tested on Django1.7

    def set_email_as_unique():
        """
        Sets the email field as unique=True in auth.User Model
        """
        email_field = dict([(field.name, field) for field in MyUser._meta.fields])["email"]
        setattr(email_field, '_unique', True)
    
    #this is called here so that attribute can be set at the application load time
    set_email_as_unique()
    
    0 讨论(0)
  • 2020-11-27 12:17

    Django has a Full Example on its documentation on how to substitute and use a Custom User Model, so you can add fields and use email as username.

    0 讨论(0)
提交回复
热议问题