I had succeeded in making authentication with token authentication mechanism in django rest framework but when i call logout function it showing error 'AnonymousUser' object has no attribute 'auth_token', don't know why it returning AnonymousUser.
## Serializer ##
class AdminLoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
username = data.get("username", "")
password = data.get("password", "")
if username and password:
user = authenticate(username=username, password=password)
if user:
if user.is_active:
data["user"] = user
else:
msg = 'User is deactivated'
raise exceptions.ValidationError(msg)
else:
msg = "Unable to login with given credentials"
raise exceptions.ValidationError(msg)
else:
msg = 'Must Provide Username and password'
raise exceptions.ValidationError(msg)
return data
## Viewsets ##
class AdminLoginView(APIView):
def post(self, request):
serializer = AdminLoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
# django_login(request, user)
token, created = Token.objects.get_or_create(user=user)
return Response({"token": token.key, 'id': token.user.id}, status=200)
class AdminLogoutView(APIView):
authentication_classes = [TokenAuthentication]
def post(self, request):
# django_logout(request)
**request.user.auth_token.delete()**
return Response(status=204)