3

error page

If any request failed to authenticate this view, the user is getting the default Django-Rest page. How I can customize this response in case of an unauthorized request.

@api_view(['GET'])
@authentication_classes([JWTTokenUserAuthentication])
@permission_classes([IsAuthenticated])
def home_view(request):
-----
JPG
  • 82,442
  • 19
  • 127
  • 206
  • specifically, DRF [custom exception handling](https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling) – JPG May 05 '21 at 15:12
  • @JPG I am not sure this question deserves to be closed. He's asking about a custom message for the authentication and that's very specific. Your link does not provide an answer for that (serializer for the SO reference, creating custom exception in DRF doc). – Guillaume May 05 '21 at 15:27
  • @Guillaume Agreed, The link by JPG does not answer my question – vivek kumar choubey May 05 '21 at 15:49

1 Answers1

4

You can create a custom EXCEPTION_HANDLER function as,

from rest_framework.views import exception_handler
from rest_framework.exceptions import NotAuthenticated
from rest_framework.response import Response


def custom_exception_handler(exc, context):
    if isinstance(exc, NotAuthenticated):
        return Response({"custom_key": "custom message"}, status=401)

    # else
    # default case
    return exception_handler(exc, context)

and then, wire-up this new custom function in your settings as,

REST_FRAMEWORK = {
    # other settings
    "EXCEPTION_HANDLER": "dotted.path.to.the.custom.function"

}

and thus, you'll get a result as below,

enter image description here

JPG
  • 82,442
  • 19
  • 127
  • 206
  • Thank you for your response. I have implemented this and getting a customer message. Is there any way I can return a custom HTML page for unauthorised access? – vivek kumar choubey May 05 '21 at 18:53