How to restrict so that the author of the post can only see and edit his posts

In this code only the author of the post can edit his post, but how to also make so that the author of the post can see only his posts?

from rest_framework import permissions


class IsAuthorOrReadOnly(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user.is_authenticated:
            return True
        return False

    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.author == request.user

Please add a link to useful reading materials

My views.py:

class TaskList(generics.ListCreateAPIView):
# permission_classes = (IsAuthorOrReadOnly,)
queryset = Task.objects.all()
serializer_class = TaskSerializer

class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
# permission_classes = (IsAuthorOrReadOnly,)
queryset = Task.objects.all()
serializer_class = TaskSerializer

If you want the author to see his posts, you can simply restrict all users from accessing the object. Like this:

from rest_framework import permissions


class IsAuthorOrReadOnly(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user.is_authenticated:
            return True
        return False

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

Now, regardless of any types of request methods, only the author can access the object.

But if you have a list view and you do not want the author to see other posts, you can try like this:

class TaskList(generics.ListCreateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

    def get_queryset(self):
        return super().get_queryset().filter(author=self.request.user)

class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

    def get_queryset(self):
        return super().get_queryset().filter(author=self.request.user)

Or combine them in a viewset:

class TaskViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing tasks.
    """
    permission_classes = [IsAuthenticated,]
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

    def get_queryset(self):
        return super().get_queryset().filter(author=self.request.user)

More information can be found in documentation

Back to Top