在django-rest-framework中,如何才能拥有只能由创建它的用户编辑的资源?

时间:2012-09-14 11:30:28

标签: django permissions django-rest-framework

如果我有这个:

class Image(models.Model):
    user = models.ForeignKey(User)

如何编写允许任何人使用GET的资源,但仅当request.userimage.user相同时PUT?

1 个答案:

答案 0 :(得分:1)

创建模型视图集使用的权限

class CreatorPermissions(BasePermission):
    def has_permission(self, request, view):
        return request.method in permissions.SAFE_METHOD

    def has_object_permission(self, request, view, obj):
        return request.user.id == obj.user.id

class ImageViewSet(viewsets.ModelViewSet):
    model = Image
    serializer_class = ImageSerializer # you have to create this
    permission_classes = (CreatorPermissions,)
    queryset = Image.objects.all()