gpt4 book ai didi

django - django 中的自定义身份验证不起作用

转载 作者:行者123 更新时间:2023-12-04 15:48:59 25 4
gpt4 key购买 nike

我是 Django 的新手,我想在 email 上对用户进行身份验证或 usernamepassword因此我编写了一个自定义身份验证,如文档中所示,但它似乎没有被调用,我不知道我该怎么做?

设置.py

AUTHENTICATION_BACKENDS = ('accounts.backend.AuthBackend',)

View .py
def login(request):
if request.method == 'POST':
username_or_email = request.POST['username']
password = request.POST['password']
user = authenticate(username=username_or_email, password=password)
print(user)
if user is not None:
return reverse('task:home')
else:
messages.error(request, "Username or password is invalid")
return render(request, 'accounts/login.html')
else:
return render(request, 'accounts/login.html')

后端.py
from django.contrib.auth.models import User
from django.db.models import Q


class AuthBackend(object):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False

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

def authenticate(self, username, password):
print('inside custom auth')
try:
user = User.objects.get(
Q(username=username) | Q(email=username) )
print(user)
except User.DoesNotExist:
return None
print(user)
if user.check_password(password):
return user
else:
return None

我写了这个 print我类(class)中的语句以检查它们是否被调用并写入控制台。但是,它们并没有被打印出来,而且 print声明于 views.py版画 None

最佳答案

您需要extend ModelBackend来自 django.contrib.auth.backends

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

User = get_user_model()

class AuthBackend(ModelBackend):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False

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

def authenticate(self, request, username=None, password=None):
print('inside custom auth')
try:
user = User.objects.get(
Q(username=username) | Q(email=username) )
print(user)
except User.DoesNotExist:
return None
print(user)
if user.check_password(password):
return user
else:
return None

还有 settings.py不要忘记添加您的自定义后端身份验证
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'accounts.backend.AuthBackend'
]

另一种可能的解决方案

从你的代码中我看到的是你想要你的 email应视为 User 的用户名模型。您可以轻松修改 Django's AbstructUser模型如下
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
# your necessary additional fields
USERNAME_FIELD = 'email' # add this line

现在 email字段将视为 user_name 字段。无需添加自定义 authentication-backend

关于django - django 中的自定义身份验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54651410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com