Django Restframework has_object_permission()函数不适用于对象权限

时间:2016-10-24 18:24:03

标签: python django

我正在调试自定义权限类并为has_object_permission()函数返回值False,但我仍然可以通过Restframework&访问我的API(GET请求) #39;没有进行身份验证的API浏览器,我无法理解原因。任何帮助将不胜感激。请参阅下面的代码。无论出于何种原因,似乎我的has_object_permission函数没有执行。请帮忙

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

1 个答案:

答案 0 :(得分:1)

Django Rest API Guide says

  

另请注意,通用视图仅检查检索单个模型实例的视图的对象级权限。如果需要对列表视图进行对象级别过滤,则需要单独过滤查询集。有关详细信息,请参阅filtering documentation

rest_framework.generics.BulkModelViewSet,顾名思义,进行批量操作。这意味着您必须使用文档中建议的对象级过滤。

你应该特别注意this部分。密切关注示例并使用代码。您还应该阅读DjangoModelPermissions以了解上述链接中的示例如何运作。