使用自定义用户模型进行Django身份验证,并将email-id作为唯一密钥

时间:2015-08-11 07:59:23

标签: python django django-models django-views django-authentication

在email-id上实现唯一约束(不重复默认用户模型字段)我做了这个

from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
    # some extra fields
    class Meta:
        unique_together = ('email', )

然后在设置文件AUTH_USER_MODEL = 'myApp.User'

mysql表将列(用户名和电子邮件)显示为UNI密钥。

到目前为止看起来不错,但在身份验证时,我不确定我在哪里弄错了。但它没有工作/登录

当用户名是唯一密钥时,此代码有效,我们通过用户名而不是电子邮件登录。

任何帮助/潜在客户都将不胜感激。

编辑:我是否必须编写自定义的modelBackend(此处解释为http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) 但不确定如何,我在这里看到了很多代码https://github.com/django/django/blob/master/django/contrib/auth/init.py

1 个答案:

答案 0 :(得分:2)

你需要像这样定义backends.py:

from django.contrib.auth.models import User, check_password

class EmailAuthBackend(object):
"""
Email Authentication Backend

Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""

def authenticate(self, username=None, password=None):
    """ Authenticate a user based on email address as the user name. """
    try:
        user = User.objects.get(email=username)
        if user.check_password(password):
            return user
    except User.DoesNotExist:
        return None 

def get_user(self, user_id):
    """ Get a User object from the user_id. """
    try:
        return User.objects.get(pk=user_id)
    except User.DoesNotExist:
        return None

在您的设置文件中添加以下内容:

AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',)

这将启用电子邮件登录。

有关详细信息,请访问this