Returning custom message when a permission is denied in DRF

前端 未结 7 1954
盖世英雄少女心
盖世英雄少女心 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:04

    From DRF

    you can simply add message attribute.

    from rest_framework import permissions
    
    class IsSuperUserPermission(permissions.BasePermission):
        message = 'User is not superuser'
    
        def has_permission(self, request, view):
            return self.request.user.is_superuser
    

    It will return a dict with key detail, something like this:

    {
        'detail': 'User is not superuser'
    }
    

    But what if you want for example that the dict key not to be detail but errors for example, it will be the same how return errors DRF.

    We can set message attribute not to string but to dict, something like this:

    class IsSuperUserPermission(permissions.BasePermission):
        message = {'errors': ['User is not a superuser']}
    
        def has_permission(self, request, view):
            self.message['errors'].clear()
            return self.request.user.is_superuser
    

    In this case the error will be:

    {
        'errors': ['User is not a superuser']
    }
    

提交回复
热议问题