Alberto Villacorta
Alberto Villacorta

Reputation: 81

Default permissions class for DRF

Django rest framework currently has IsAdminUseras 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

Answers (2)

Devansh
Devansh

Reputation: 1267

permissions.py

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 

views.py

from .permissions import IsOwnerOrAdminUser

class UserAPIView(APIView):
    permission_classes = (IsOwnerOrAdminUser, )

Upvotes: 3

neverwalkaloner
neverwalkaloner

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

Related Questions