In django-rest-framework, how can I have a resource that is only editable by the user that created it?

StackOverflow https://stackoverflow.com/questions/12423648

質問

If I have this:

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

how can I write a resource that will allow GET from anyone, but PUT only when request.user is the same as image.user?

役に立ちましたか?

解決

Create a permission that your modelviewset uses

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() 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top