Reputation: 81
Django rest framework currently has IsAdminUser
as a permissions class is there also a corresponding IsOwnerOrAdminUser
? Something to that affect? It seems like there should be something that only allows an object to have CRUD functionality if the current user is the one that created it. I'm using DRF with djangorestframework-jwt
Upvotes: 1
Views: 898
Reputation: 1267
from rest_framework import permissions
class IsOwnerOrAdminUser(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user or request.user.is_staff
from .permissions import IsOwnerOrAdminUser
class UserAPIView(APIView):
permission_classes = (IsOwnerOrAdminUser, )
Upvotes: 3
Reputation: 47354
You can find full list of rest-framework permissions in docs. There is DjangoModelPermissionsOrAnonReadOnly
which allows no-safe methods only for users with add, change and delete permissions on models.
If it's not fit your requrements you can implement your own permission class something like this:
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user or request.user.is_superuser
This method is documented here.
Upvotes: 3