我为 Auth 后端编写了以下类,并将其放置在应用程序目录内的文件“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")
但我得到以下跟踪:
ImportError at /login Module "events" does not define a "authentication" attribute/class
我是一个菜鸟,我很确定我做错了什么,我只是不明白它是什么。
有人可以告诉我该怎么做吗?
最佳答案
您还需要使用类名导入它,因此:
AUTHENTICATION_BACKENDS = [
<b>'events.authentication.authBackend'</b>
]
在您的authBackend
中,您还犯了一些错误。首先是认证后端needs to implement a number of functions [Django-doc] :
The user model and its manager will delegate permission lookup functions (
get_user_permissions()
,get_group_permissions()
,get_all_permissions()
,has_perm()
,has_module_perms()
, andwith_perm()
) to any authentication backend that implements these functions.
因此,您也需要实现此功能。因此,继承 BaseBackend
[Django-doc] 可能会更好。或者也许更好的是 ModelBackend
,因为这已经实现了逻辑,因此您只需重写某些函数即可使其与您的新模型一起使用。
您还在参数名称中犯了一个拼写错误:它是 password
,而不是 :passwprd
from django.contrib.auth.backends import <b>BaseBackend</b>
from events.models import User
class authBackend(<b>BaseBackend</b>):
def authenticate(self, request, username<b>, password</b>):
try:
user = User.objects.get(rollNo=username)
success = user.check_password(<b>password</b>)
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
Note: According to the PEP-8 Style guide [pep-0008], class names are written in PerlCase starting with an uppercase, so you might want to consider renaming
toauthBackend
AuthBackend
.
关于python - 如何在 django 项目的 settings.py 文件中将身份验证后端设置为默认(扩展 AbstractBaseUser 模型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66397239/