I have an API view (using DJ Rest Framework) that I am posting to via React in my frontend. request.user.is_authenticated
returns True here (and returns the user I have attempted to sign-in as), however, in my view for rendering the login page template, request.user.is_authenticated
returns False, and the user object is an AnonymousUser
.
Why is this?
I've checked this question , but it only has information on templates.
Here's the API view code:
@api_view(['POST'])
def login_api_view(request, *args, **kwargs):
if request.user and request.user.is_authenticated:
return Response({'message': 'User is already authenticated'}, status=400)
username = request.data.get('username')
password = request.data.get('password')
if username is None or password is None:
return Response({'message': 'Please specify a username and password'}, status=400)
user = authenticate(request, username=username, password=password)
if user is None:
return Response({'message': 'Invalid credentials'}, status=401)
login(request, user)
return Response({'message': 'Successfully authenticated user'}, status=200)
And here's the code for the template:
def login_view(request, *args, **kwars):
if request.user.is_authenticated:
return redirect('/')
return render(request, 'users/login.html')
在停止这方面的工作几天并回到它之后,我发现我的 Dev Authentication 类( rest_framework.authentication.BasicAuthentication
)弄乱了我的结果。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.