本文介绍了Django登录AttributeError:"AnonymousUser"对象没有属性"_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:

也许是因为我将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身份验证提供了一个库.它同时提供令牌生成和验证.

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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 15:46