How to set email as a Django username

Asked

Viewed 198 times

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 the user name will be, when I change the value to email (name of my email field) when creating 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 someone tell me the right way to do this ?

1 answer

0

You must 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

Then set that up Authentication backend as your back-end authentication in your Settings:

AUTHENTICATION_BACKENDS = ['path.to.auth.module.EmailBackend']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.