lionheart
lionheart

Reputation: 11

Not using user = models.OneToOneField(User,on_delete=models.CASCADE)

I am creating the registration,login, logout which requires only email and password. When I use user = models.OneToOneField(User,on_delete=models.CASCADE) it gives me an error because it requires username too. How can I take only email and password from User and save it to user?

Upvotes: 1

Views: 717

Answers (1)

shoytov
shoytov

Reputation: 605

You can use

AUTHENTICATION_BACKENDS = ('path_to_file.EmailAuthBackend', 'django.contrib.auth.backends.ModelBackend',)

in settings

and backend file:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User

class EmailAuthBackend(object):

    @staticmethod
    def authenticate(self, username="", password="", **kwargs):
        user_model = get_user_model()

        try:
            user = user_model.objects.get(email=username)
            if check_password(password, user.password):
                return user
            else:
                return None
        except user_model.DoesNotExist:
            return None

    @staticmethod
    def get_user(user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

and add unique email rule in your models

from django.contrib.auth.models import User    
User._meta.get_field('email')._unique = True

Upvotes: 1

Related Questions