我尝试在用户身份证上扫描RFID标签后尝试登录用户,但是在致电auth.login()
后,用户未登录,且request.user
仍在{ {1}}。
我使用以下视图对用户进行身份验证:
AnonymousUser
我还有一个自定义身份验证后端来检查徽章编号:
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
try:
Models.People.objects.get(id_badge=form.cleaned_data['badge_number'], deleted=False, system_user=True)
except Models.People.DoesNotExist:
form.add_error('badge_number', 'Badge number not recognised')
return render(request, 'login.html', {'form':form})
user = user.authenticate(id_badge=form.cleaned_data['badge_number'])
if user is not None:
auth.login(request, user)
return redirect(reverse('main-menu'))
else:
form.add_error('badge_number', 'Badge number not recognised')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
尝试登录时,用户已成功重定向到菜单页面,但是当模板尝试将其名称放在页面上时,模板会引发错误:
class RFIDBackend(object):
def authenticate(id_badge=None):
try:
person = Models.People.objects.get(info1=id_badge, deleted=False, system_user=True)
except Models.People.DoesNotExist, Models.People.MultipleValuesReturned:
return None
try:
user = User.objects.get(username=person.login)
except User.DoesNotExist:
return None
if user.is_active:
return user
return None
def get_user(id_badge=None):
try:
person = Models.People.objects.get(info1=id_badge, deleted=False, system_user=True)
except Models.People.DoesNotExist, Models.People.MultipleValuesReturned:
return None
try:
user = User.objects.get(username=person.login)
except User.DoesNotExist:
return None
return user
答案 0 :(得分:1)
它应该是cleaned_data
而不是cleaned_date
?
Models.People.objects.get(id_badge=form.cleaned_data['badge_number'], deleted=False, system_user=True)
答案 1 :(得分:1)
您的get_user
方法应该使用用户的主键,而不是id_badge
。由于您使用的是内置用户,因此您可以使用与Django的ModelBackend
相同的实现。
from django.contrib.auth import get_user_model
class RFIDBackend(object):
...
def get_user(self, user_id):
UserModel = get_user_model()
try:
return UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
您尝试对此进行扩展,以便对deleted
和system_user
字段进行检查。如果你这样做,测试以确保在删除用户时它按预期工作,我不是100%肯定它会导致用户被注销。