Django REST multiple permission class not working

I have two permission class. IsAuthorGroup will check if the user belongs from the author group and IsOwnerOrReadOnly will restrict the user to performing post and delete if he is not the object’s owner.

But the problem is anyone from IsAuthorGroup performing post and delete request event he isn’t own of the object.

How to restrict anyone from IsAuthorGroup performing post and delete request if he isn’t owner of the object?

here is my code:

class IsAuthorGroup(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='AuthorGroup'):
            return True
        return False


class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the blog.
        return obj.author == request.user or request.user.is_superuser 



class BlogViewSet(viewsets.ModelViewSet):

    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    pagination_class = BlogPagination
    lookup_field = 'blog_slug'
    permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup]

my serializer.py

class BlogSerializer(serializers.ModelSerializer):
    author_first_name = serializers.CharField(
        source="author.first_name", required=False)
    author_last_name = serializers.CharField(
        source="author.last_name", required=False)

    class Meta:
        model = Blog
        exclude = ("author", "blog_is_published")
        lookup_field = 'blog_slug'
        extra_kwargs = {
            'url': {'lookup_field': 'blog_slug'}
        }

Hey there!
I never seen the usage of the & operator on permission_classes. Maybe did you mean to put a comma , in there?

But the problem is I don’t want to restrict my get method which means If I use [IsOwnerOrReadOnly & IsAuthorGroup] it’s asking me Authentication credentials for get request which I don’t want

Oh, i see.
So i think you want to implement the get_permissions method.
Take a look into the DRF docs.

1 Like

Thanks my problem is solved. Can you tell me how I can set request.user as my blog autor in django REST. Normally we did something like this in views instance.author == request.user when submitting forms. How I can do something like that in DRF?

Great.
For this open a new topic relating what you want to achieve, and what’s not going like you want.

what will be the action name for viewing data using slug or id? like if self.action == 'list': here list providing list of data.

It really depends on the view that you are accessing.
But when you do a GET request without the id, it’s called: list. When you give the id: detail.

Here you can read more about it.


it’s restring my details view as I am sending get request only