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:
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:
Or combine them in a viewset:
More information can be found in documentation