如何解决我如何在我的 django 项目的 settings.py 文件中将我的身份验证后端设置为默认值扩展 AbstractBaseUser 模型
我为 Auth Back end 编写了以下类并将其放置在应用程序目录中的“authentication.py”文件中:
from events.models import User
class authBackend():
def authenticate(self,request,username,passwprd):
try:
user = User.objects.get(rollNo=username)
success = user.check_password(password)
if success:
return user
except User.DoesNotExist:
pass
return None
def get_user(self,uid):
try:
return User.objects.get(pk=Uid)
except:
return None
然后我将它添加到 settings.py 中(或者至少我认为我这样做了):
AUTHENTICATION_BACKENDS = [
'events.authentication'
]
这是我登录用户的方式:
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
rollno = request.POST["rollno"]
password = request.POST["password"]
user = authenticate(request,username=rollno,password=password)
# Check if authentication successful
if user is not None:
login(request,user)
return HttpResponseRedirect(reverse("events:index"))
else:
return render(request,"events/login.html",{
"message": "Invalid roll number and/or password."
})
else:
return render(request,"events/login.html")
但我得到以下回溯:
/login 模块“事件”中的导入错误未定义“身份验证”属性/类
我是一个菜鸟,我很确定我做错了什么,我只是不明白这是什么。
有人能告诉我怎么做吗?
解决方法
您还需要使用类名导入它,因此:
AUTHENTICATION_BACKENDS = [
'events.authentication.authBackend'
]
在您的 authBackend
中,您也犯了许多错误。首先是身份验证后端 needs to implement a number of functions [Django-doc]:
用户模型及其管理器将委托权限查找功能(get_user_permissions()
、get_group_permissions()
、get_all_permissions()
、has_perm()
、has_module_perms()
和 {{1} }) 到任何实现这些功能的身份验证后端。
因此,您还需要实现这些功能。因此,从 BaseBackend
[Django-doc] 继承或从 ModelBackend
继承可能更好,因为这已经实现了逻辑,因此您只需要覆盖某些函数即可让它与您的新函数一起工作模型。
您还在参数名称中打错了字:它是 with_perm()
,而不是 :password
passwprd
注意:根据PEP-8 Style guide [pep-0008],
类名以 PerlCase 开头,以大写字母开头,因此您可能需要考虑重命名
到 from django.contrib.auth.backends import BaseBackend
from events.models import User
class authBackend(BaseBackend):
def authenticate(self,request,username,password):
try:
user = User.objects.get(rollNo=username)
success = user.check_password(password)
if success:
return user
except User.DoesNotExist:
pass
return None
def get_user(self,uid):
try:
return User.objects.get(pk=Uid)
except:
return None
authBackend
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。