不使用user = models.OneToOneField(User,on_delete = models.CASCADE)

时间:2020-03-30 12:05:28

标签: python django web django-models django-forms

我正在创建仅需要电子邮件和密码的注册,登录和注销。当我使用user = models.OneToOneField(User,on_delete = models.CASCADE)时,我也遇到了错误,因为它也需要用户名。如何仅从用户那里获取电子邮件和密码并将其保存到用户?

1 个答案:

答案 0 :(得分:1)

您可以使用

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

在设置中

和后端文件:

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

并在模型中添加唯一的电子邮件规则

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