Check permissions before receiving an object in Django REST

Using the Django REST framework, I use this view and permission to allow only project owners to receive their projects.

view.py

class ProjectViewSet(viewsets.ModelViewSet):
    permission_classes = (
       IsProjectOwner, 
       permissions.IsAuthenticated,
       )

    def get_queryset(self):
       return Project.objects.filter(owner=self.request.user)

permissions.py

class IsProjectOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user

When a user tries to get a project that does not belong to him, HTTP 404 occurs. However, I would like to get HTTP 403_Forbidden. Here is the test I'm using

    def test_auth_get(self):
        self.client.credentials(
            HTTP_AUTHORIZATION=self.authenticated_user_token
            ) 

        response = self.client.get(
            '/-/projects/%s/' % self.project_owner_project_id
            )

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

I tried to solve the problem using the get_object () method, as in the REST document http://www.django-rest-framework.org/api-guide/permissions/#object-level-permissions . But I'm not sure how to check the resolution before knowing the actual object.

+4
source share
2 answers

get_queryset; , get_queryset.

def get_queryset(self):
    if self.action == 'update':
        return Project.objects.filter(owner=self.request.user)
    else:
        return Project.objects.all()
0

get_queryset , . , .

.

0

Source: https://habr.com/ru/post/1617390/


All Articles