简体   繁体   English

在Django中使用电子邮件登录

[英]Using Email as login in Django

I am not able to login in django with correct password and email. 我无法使用正确的密码和电子邮件登录django。 here is my code. 这是我的代码。

backends.py backends.py

 from django.contrib.auth.models import User

    class Emailbackend(object):

        def authenticate(self, username=None, password=None, **kwargs):
            try:
                user = User.objects.get(email=username)
            except User.MultipleObjectsReturned:
                user = User.objects.filter(email=username).order_by('id').first()
            except User.DoesNotExist:
                return None
            if getattr(user, 'is_active') and user.check_password(password):
                return user
            return None

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

Settings.py Settings.py

AUTHENTICATION_BACKENDS = (
    'users.backends.Emailbackend',
)

Actually, authenticate method expects an argument request should be passed. 实际上, authenticate方法期望应传递参数request So you need to declare your Backend like this: 因此,您需要像这样声明您的后端:

class Emailbackend(object):

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
        # rest of the code

Reference can be found here . 参考可以在这里找到。

first check the value of user in authenticate method try block. 首先在authenticate方法try块中检查user的值。 If it get correct result then check following block what user value return. 如果得到正确的结果,则检查以下程序段返回的user值。

if getattr(user, 'is_active') and user.check_password(password):
    return user

If it doesn't work then go to your database and check is your password hash value available or not. 如果它不起作用,则转到您的数据库,检查您的密码哈希值是否可用。

Try these link link1 link2 试试这些链接link1 link2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM