django.contrib.auth.login() function not returning any user as logged in

You have to set the default auth class as session authenticate class in DRF settings. Read more about it here [1].

Session auth uses session id to identify the user. So you have to send the cookie based session id in the request. Read about session auth here [2].

for example:

        'rest_framework.authentication.SessionAuthentication', # <-- set this class

Use this code:

def post(self, request, format = None):
    serializer = UserLoginSerializer(
    if serializer.is_valid():
        user = authenticate(username=serializer.validated_data["username"], password=serializer.validated_data["password"])
        if user:
            return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)
        return Response("Invalid username/password", status=status.HTTP_401_UNAUTHORIZED)
    return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)

But my recommendation is to use Token auth [3].

To use token auth 2 things will change:

  1. The default auth class in DRF settings
  2. When sending a request to any DRF API view you to send the Auth header as Token <token-value>

Your post method and API views code will remain same.




I am using DRF for login. You can check this serializers and login view.

    class LoginSerializer(serializers.Serializer):
              username = serializers.CharField()
              password = serializers.CharField()

    def validate(self, data):
         user = authenticate(**data)
         if user and user.is_active:
               return user
    raise serializers.ValidationError("Incorrect Credentials")

login view:

    class LoginAPIView(generics.GenericAPIView):
          queryset = User.objects.all()
          permission_classes = [AllowAny]
          serializer_class = LoginSerializer

 def post(self, request, *args, **kwargs):
     serializer = self.get_serializer(
     user = serializer.validated_data
     return Response({
        "user": UserSerializer(user, context=self.get_serializer_context()).data,
        "token": AuthToken.objects.create(user)[1]
    }) rest framework classes :


    # 'rest_framework.authentication.BasicAuthentication',
    # 'rest_framework.authentication.SessionAuthentication',

'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']