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'}
}