Django登录AttributeError:'AnonymousUser'对象没有属性'_meta' [英] Django login AttributeError: 'AnonymousUser' object has no attribute '_meta'
问题描述
我有这个代码:
from django.contrib.auth import logout, login, authenticate
...
if User.objects.filter(email=email).exists():
existing_user = User.objects.get(email=email)
user = authenticate(username=existing_user.username, password=existing_user.password)
login(request, user)
根据文档,这应该可以,但它没有,它给了我错误:
According to the docs, this should work, but it doesn't, it gives me the error:
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)AttributeError:AnonymousUser"对象没有属性_meta"
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'AnonymousUser' object has no attribute '_meta'
也许问题是因为我在 Django Rest Framework 中使用 JWT 身份验证?它只是一个 django 驱动的 API,所以我想这是一个不同的场景,但我不明白是什么导致了这个问题.
Maybe the problem happens becouse I am using JWT Authentication with Django Rest Framework? It is just an django-powered API, so I guess it is a different scenario, but I don't understand what could be causing the problem.
推荐答案
在 DRF 中,用户应该在 Authentication 类中进行身份验证.这个库为 JWT auth 提供了一个.它提供令牌生成和验证.
In DRF user should be authenticated inside Authentication class. This library provides one for JWT auth. It provides both token generation and verification.
您将在 View 或 ViewSet 类中以 self.request.user
的形式获取用户.您只需要允许 JWT 身份验证:
You will get user as self.request.user
in your View or ViewSet class. You just need to allow JWT auth:
class ExampleView(APIView):
authentication_classes = (BasicAuthentication, JSONWebTokenAuthentication)
或者更好的设置是 DEFAULT_AUTHENTICATION_CLASSES
记录在 这里.
Or better set is as DEFAULT_AUTHENTICATION_CLASSES
as documented here.
这篇关于Django登录AttributeError:'AnonymousUser'对象没有属性'_meta'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!