Home > Back-end >  Djnago rest framework how to allow only update user own content only
Djnago rest framework how to allow only update user own content only

Time:06-21

I don't want to allow any user update another user object. I want to allow only update user own content. here is my code:

models.py

class Blog(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    blog_title = models.CharField(max_length=200, unique=True)

views.py

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    pagination_class = BlogPagination
    lookup_field = 'blog_slug'
    

    def update(self, request, slug=None):
        pass

CodePudding user response:

You can use object level permissions. Create a custom permission class called IsOwnerOrReadOnly

from rest_framework import permissions


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

Then, add this permission to BlogViewSet:

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    pagination_class = BlogPagination
    lookup_field = 'blog_slug'
    permission_classes = [IsOwnerOrReadOnly]
  • Related