custom message in raise PermissionDenied not working in Django rest

Issue

I tried raise PermissionDenied("Anonymous user") inside a custom permission function but the message I wrote is not showing in the api response. Instead, it is showing the default forbidden message that says you dont have permission to perform this action

My snippet is here:

class CustomPermission(BasePermission):
    """
        returns permission based on the request method and slug
    """

    def has_permission(self, request,view):
        slug = request.resolver_match.kwargs["slug"]
        if slug is not None and request.method == 'POST':
            if slug == "abc":
                user = request.user
                if user.is_staff:
                    return True
                if user.is_anonymous:
                    print("iam here")
                    raise PermissionDenied("Anonymous user")
            elif slug == "mnp":
                return True
        else:
            return True

Here in the above code I reached to ("iam here") but anonymous user is not printing instead showing the default message.

Solution

You can change error message in message property:

from rest_framework import permissions


class CustomerAccessPermission(permissions.BasePermission):
    message = 'Your message'

    def has_permission(self, request, view): 
        ... # return True or False

Docs in : https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

After that, the permission_denied(self, request, message=None, code=None) function in your view would be called which message is the attribute that you have declared in your permission class.

You can use that, or even pass another message:

from rest_framework.exceptions import PermissionDenied


class YourView(...):
    permission_classes = [CustomerAccessPermission]

    def permission_denied(self, request, message=None, code=None):
        raise PermissionDenied(message)

Answered By – Amin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published