djangopermissionsdjango-rest-framework

Returning custom message when a permission is denied in DRF


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 are some API methods in which a "Permission denied" generic message is not very informative for the user. For example, if the user is authenticated but the account has expired, it would be nice to let the user know that his account is expired and not just a permission denied error.

When building custom permission classes, you either return True or False - according to the documentation. But I would like, as said above, to show a more informative message to the user. How to accomplish this?


Solution

  • Since DRF 3.2.0, You only have to add a message attribute :

    from rest_framework import permissions
    
    class CustomerAccessPermission(permissions.BasePermission):
        message = 'Adding customers not allowed.'
    
        def has_permission(self, request, view): 
    

    See from DRF documentation: http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions