Search code examples
pythondjango-rest-frameworkdjango-permissions

Django-REST: custom permission doesn't work


I'm trying to make a custom permission using this guide

views.py

class CustomModelList(generics.ListAPIView):
    queryset = CustomModel.objects.all()
    serializer_class = CustomModelSerializer
    permission_classes = [IsAuthenticatedOrReadOnly, IsCustomOrReadOnly]

    def get(self, request, format=None):
        # some logic

    def post(self, request, format=None):
        # some logic

Just for experiment I've created this permission not to apply anyway

pesmissions.py

class IsCustomOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        return False

But when POST request sends to server it takes no effect -- I'm able to create new model instance.


Solution

  • I think that since you are using a list view, custom object level permissions are not checked automatically.

    Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.

    You can try overriding the has_permission method instead and see if that works, or check the permissions manually.