[Django]-Django Rest Framework – permission to create

5πŸ‘

βœ…

I found out what I had to do. Here is my new permission class:

class LinkAssetPermission(permissions.BasePermission):
    message = 'Link access not allowed.'

    def has_permission(self, request, view):
        try:
            content = Content.objects.get(pk=request.parser_context["kwargs"]["content_id"])
        except:
            return False

        return content.delivery.owner == request.user and content.delivery.can_change

    def has_object_permission(self, request, view, obj):
        return obj.content.delivery.owner == request.user and obj.content.delivery.can_change

On create the method has_object_permission is not considered but the has_permission is. So I retrieve the parameter sent from the urls.py, query and check the properties of the object I want.

Thanks

πŸ‘€AndrΓ© Luiz

1πŸ‘

has_object_permissions() gets called whenever .get_object() method is called in a generic view i.e. a particular resource is being accessed.

Now, all the detail requests (retrieve, update, delete) access a particular resource/object, it works. For create requests, get_object() method does not get called, so it does not work in your case.

For handling create requests, you can create another serializer where there is validations for the above 2 conditions. And then change your permission classes to work for detail requests only.

πŸ‘€Rahul Gupta

Leave a comment