[Django]-DRF: Always apply default permission class

0👍

The permissions attribute takes a list of classes so you just have to include the default.

class ModelViewSet(viewsets.ModelViewSet):
    permission_classes = (
        DefaultPermission,
        CustomPermission,
    )

0👍

DEFAULT_PERMISSION_CLASSES will only be applied when you do not declare permission_classes in your viewset.

If you do not have any other permission classes that need to apply, simply exclude permission_classes from your viewset, that way it will always use the default.

If there is a time where you will need to use another permission class as well as the default.

eg

class HasPermission(permissions.BasePermission):

    def has_permission(self, request, view, obj=None):
        if hasattr(view, 'permission_required'):
            return request.user.has_perm(view.permission_required)
        return True

class AnotherPermissionClass(..):
    ....

where HasPermission always needs to be applied and sometimes AnotherPermissionClass` may need to also be applied.

If this is the case, then just inherit HasPermission as a base class for AnotherPermissionClass.


AnotherPermissionClass(apps.api.permissions.HasPermission)
     def has_permmision(self, request, view, obj=None):
         has_base_perm = super().has_permmision(request, view, obj=obj)
         ...

class ViewsetA(...):
     ...

     # Don't declare permission_classes at all and it will use the settings default


class ViewsetB(...):
     permission_classes = (AnotherPermissionClass,)

Leave a comment