Returning custom message when a permission is denied in DRF

前端 未结 7 1959
盖世英雄少女心
盖世英雄少女心 2021-02-13 01:20

Django REST Framework has an excellent piece of documentation about permissions. I\'ve been able to use pre-made permission classes and also built my own.

However, there

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 02:14

    You can send more than a single customized message if you want to. You can do it using GenericAPIException.

    Step 1: Create a permissions.py file and write this code.

    class Check_user_permission(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.method in permissions.SAFE_METHODS:
            return True
        else:
            response ={
                "success": "false",
                'message': "Post request is not allowed for user from admin group",
                "status_code":403,
            }
            raise GenericAPIException(detail=response, status_code=403)
    

    Here, response is the JSON response you want to send.

    Step 2: Go to view.py file and add the class Check_user_permission in the permission_classes list this way:

    class UserList(APIView):
        permission_classes = (IsAuthenticated, Check_user_permission)
        authentication_class = JSONWebTokenAuthentication
        ... 
        ...
    

    Now if you go to the endpoint and send a POST request you'll get this response.

    {
    "success": "false",
    "message": "Post request is not allowed!",
    "status_code": 403
    }
    

提交回复
热议问题