Django 1.9 check if email already exists

后端 未结 1 1803
甜味超标
甜味超标 2021-01-03 09:22

My site is set up so there is no username (or rather user.username = user.email). Django has an error message if a user tries to input a username that is already in the data

相关标签:
1条回答
  • 2021-01-03 09:43

    You can override the clean_<INSERT_FIELD_HERE>() method on the UserForm to check against this particular case. It'd look something like this:

    forms.py:

    class UserForm(forms.ModelForm):
        class Meta:
            model = User
            fields = ('email',)
    
        def clean_email(self):
            # Get the email
            email = self.cleaned_data.get('email')
    
            # Check to see if any users already exist with this email as a username.
            try:
                match = User.objects.get(email=email)
            except User.DoesNotExist:
                # Unable to find a user, this is fine
                return email
    
            # A user was found with this as a username, raise an error.
            raise forms.ValidationError('This email address is already in use.')
    
    class UserProfileForm(forms.ModelForm):
        class Meta:
            model = UserProfile
            fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
    

    You can read more about cleaning specific fields in a form in the Django documentation about forms.

    That said, I think you should look into creating a custom user model instead of treating your User Profile class as a wrapper for User.

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