C. Gary
C. Gary

Reputation: 123

Django Restframework has_object_permission() function is not working for object permission

I'm in the process of debugging my custom permissions class and returning a value of False for my has_object_permission() function, but my I'm still able to access my API (GET request), via Restframework's API browser without authenticating and I can't understand why. Any help would be greatly appreciated. Please see code below. for whatever reasons, it appears that my has_object_permission function is not executing. Please Help

urls.py

router = BulkRouter()
router.register(r'api1', SimpleViewSet1)


urlpatterns = [
    url(r'^test/', include(router.urls, namespace='api1')),
]

views.py

class SimpleViewSet1(generics.BulkModelViewSet):    
    queryset = Barcode.objects.all()
    permission_classes = (MyUserPermission,)
    serializer_class = SimpleSerializer1


    def get_queryset(self):
        user = User.objects.get(pk=2)
        return Barcode.objects.filter(owner = user)


    def get_object(self):
        obj = get_object_or_404(self.get_queryset())
        self.check_object_permissions(self.request, obj)
        return obj

permissions.py

class MyUserPermission(BasePermission):

    def has_permission(self, request, view):
        return True


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

serializer.py

class SimpleSerializer1(BulkSerializerMixin,  # only required in DRF3
                       ModelSerializer):

    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta(object):
        model = Barcode
        # only required in DRF3
        list_serializer_class = BulkListSerializer
        fields = ('barcode_number', 'barcode_type', 'owner')

models.py

@python_2_unicode_compatible
class Barcode(models.Model):
    owner = models.ForeignKey('auth.User', related_name = 'barcodes')
    barcode_number = models.CharField(max_length=200)
    barcode_type = models.CharField(max_length=200)

    def __str__(self):
        return self.barcode_number

Upvotes: 0

Views: 1220

Answers (1)

an0o0nym
an0o0nym

Reputation: 1516

Django Rest API Guide says:

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.

rest_framework.generics.BulkModelViewSet, as it's name suggests,does bulk operations. It means that you have to use object-level filtering as proposed in the docs.

You should be looking especially under this section. Pay close attention to the example and make use of the code. You should also read about the DjangoModelPermissions to understand how does the example in the link above works.

Upvotes: 1

Related Questions