Search code examples
jsondjangodjango-rest-frameworkaxiospostman

Django Rest Framework session authentication default view JSON Parse


I'm making a user session auth via DRF, React and Axios. I also use Postman for testing my endpoints. So the question is how to make default login view from rest_framework.urls work with JSON format. When I send user data (username and password) via form-data radio button inside Postman everything is working as intended. But when I use JSON format inside both Postman and Axios the DRF endpoint returns such html page:

enter image description here

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
    ]
}

urls.py

urlpatterns = [
    path('drf-auth/', include('rest_framework.urls')),
]

My JSON data

{"username": "admin", "password": "admin"}

Solution

  • Default rest_framework.urls login view accepts form data and returns a JSON response. Does not accept JSON data. To fix this, create a custom login view, and then use the functions authenticate and login in the view. This will accept JSON data.

    views.py

    class CustomLoginView(APIView):
        def post(self, request):
            user=authenticate(request, username=request.data.get("username"), password=request.data.get("password"))
            if user is not None:
                login(request, user)
                return Response... # success response
            else:
                return Response .... # error response