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
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
}