python - Django 身份验证 login() 返回匿名用户
问题描述
我正在尝试登录到一个不是默认数据库的数据库,为此我编写了一个自定义身份验证代码,但是每当我尝试登录时,该方法都会返回一个AnonymousUser
. 我不知道为什么要这样做,因为用户身份验证是使用该authenticate
方法正确完成的。
任何帮助将非常感激。
我的文件
视图.py
def login_authentication(request):
if request.method == "POST":
form = New_Login_Form(request.POST)
# print(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user_operating_company = request.POST['user_operating_company']
user = authenticate(request, email=email,
password=password, db=user_operating_company)
if user:
login(request, user, user_operating_company)
return redirect('test')
else:
form = New_Login_Form()
return render(request, 'index.html', {'form': form})
后端.py
from django.contrib.auth.backends import ModelBackend
from .models import Account
class CustomAuthenticate(ModelBackend):
def authenticate(self, request, email=None, password=None, db=None):
try:
user = Account.objects.all().using(db).get(email=email)
if user.check_password(password):
return user
except:
return None
def get_user(self, request, email, db):
try:
return Account.objects.using(db).get(pk=email)
except:
return None
并且在
设置.py
AUTHENTICATION_BACKENDS = ('accounts.backends.CustomAuthenticate', 'django.contrib.auth.backends.ModelBackend')
编辑:
我根据@schillingt 的回答进行了更改,更新后的后端是:
from django.contrib.auth.backends import ModelBackend
from .models import Account
class CustomAuthenticate(ModelBackend):
def authenticate(self, request, email=None, password=None, db=None):
self.db = db
try:
user = Account.objects.using(db).get(email=email)
if user.check_password(password):
return user
except Account.DoesNotExist:
return None
def get_user(self, email):
try:
user = Account.objects.using(self.db).get(pk=email)
except Account.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
但现在它给了我一个错误,上面写着
'CustomAuthenticate' object has no attribute 'db'
解决方案
我相信你的签名有误get_user
。ModelBackend 是:
def get_user(self, user_id):
try:
user = UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
此方法由django.contrib.auth.get_user
. 您的后端是否引用了db
应该使用的实例?或者是在请求中定义的?如果它是在请求中定义的,您可能必须修改该django.contrib.auth.get_user
方法以向后端方法的调用提供正确的参数,get_user
以便您拥有正确的db
实例。
编辑:
这让人觉得我错了。你不应该猴子补丁django.contrib.auth.get_user
。您应该能够在后端实例上设置 db 实例authenticate
,然后在get_user
.
推荐阅读
- azure - 当大小 > 50 MB 的文件到达 sftp 服务器时,将副本复制到 Azure 存储中
- vhdl - 倒数无符号数时每 10 个都缺少 9 和 8
- ios - 如何使用 Firebase 存储中的图像填充 UICollectionView 单元格?
- python - 使用 ax.text,matplotlib 相对于轴定位字体
- batch-file - 批处理调用管理批处理,变量不交叉
- python - 是否可以使用 C# 和 Python 创建桌面应用程序来创建现代 GUI
- python - 如何在 Python Seaborn 的线图中的每个标记上添加值/标签?
- javascript - 如何创建检查 div 元素样式的事件侦听器?
- python - Python Dataframe 将数据框列表的列表转换为单个数据框
- c - 我的函数返回分段错误错误,显然没有错