问题
after logging in the user and checking whether request.user isauthenticated in other activity in android. the value is always false.
the following code is used for login a user
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,logout,login
@api_view(['POST'])
def userRegister(request):
user=User.objects.create_user(username=request.POST['username'],email=request.POST['email'],password=request.POST['password'])
return Response({'ok':'True'},status=status.HTTP_201_CREATED)
@api_view(['POST'])
def userLogin(request):
user=authenticate(
username=request.POST['username'],
password=request.POST['password']
)
if user is not None:
login(request,user)
return Response({'ok':'True'},status=status.HTTP_200_OK)
else:
return Response({'ok':'False'},status=status.HTTP_401_UNAUTHORIZED)
the following code is used to check whether the user is authenticated or not
from rest_framework.response import Response
from rest_framework.decorators import api_view
from . import models
from . import serializers
from django.contrib.auth.models import User
from rest_framework import status
@api_view(['GET'])
def HomeView(request):
if request.user.is_authenticated:
return Response(data={"ok":'true'})
else:
return Response(data={"ok":"false"})
回答1:
In your view (if you are using a version of Django < 1.10, as @Kevin Christopher Henry points out in the comments below) you need to do:
if request.user.is_authenticated():
If you do .is_authenticated
(without the parentheses) it will return the method itself instead of a boolean (True
or False
), and will always evaluate to True
, or at least it should. I am not sure why it would return False
in your case, but I think this should solve your problem.
Also, note that in Django templates the situation is different. In a template you can (and must) do:
{% if user.is_authenticated %}
Note the lack of parentheses after is_authenticated
. If you include parentheses in the template case, you will get an error, while if you don't include them in the view case you will get unexpected results.
来源:https://stackoverflow.com/questions/39318335/request-user-is-authenticated-always-returns-false