How to set email as username in django

1

I have the following code to create a custom User:

from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin,UserManager

class User(AbstractBaseUser,PermissionsMixin):

    username = models.CharField('Nome de Usuário',max_length=30,unique=True)
    email = models.EmailField('E-mail',unique=True)
    name = models.CharField('Nome',max_length=100,blank=True)
    is_active = models.BooleanField('Está Ativo?',blank=True,default=True)
    is_staff = models.BooleanField('É da Equipe?',blank=True,default=False)
    date_joined = models.DateTimeField('Data de Entrada',auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.name or self.username

    def get_short_name(self):
        return self.username

    def get_full_name(self):
        return str(self)

    class Meta:
        verbose_name = 'Usuário'
verbose_name_plural = 'Usuários'

I believe that the field "USERNAME_FIELD = 'username'" defines what will be the username, when I change the value to email (name of my email field) when I create a super user, User now and email but soon after entering the password for the second time an error occurs with reference to the username.

Can anyone tell me the correct way to do this?

    
asked by anonymous 28.03.2017 / 14:11

1 answer

0

You should write a custom authentication backend . Something like this will work:

from django.contrib.auth import get_user_model

class EmailBackend(object):
    def authenticate(self, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if getattr(user, 'is_active', False) and  user.check_password(password):
                return user
        return None

Next, set this authentication backend as your authentication back-end to your settings :

AUTHENTICATION_BACKENDS = ['path.to.auth.module.EmailBackend']
    
11.05.2017 / 10:54