Skip to content

Instantly share code, notes, and snippets.

@Kobold
Created April 17, 2015 08:24
Show Gist options
  • Select an option

  • Save Kobold/c5ead2b72b2be03eb0ca to your computer and use it in GitHub Desktop.

Select an option

Save Kobold/c5ead2b72b2be03eb0ca to your computer and use it in GitHub Desktop.
IsOwner - Custom django-rest-framework permission to only allow owners of an object to edit it.
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_permission(self, request, view):
return request.user and request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
return obj.user == request.user
@MaggieChege
Copy link
Copy Markdown

MaggieChege commented Feb 2, 2019

How do I restrict permissions to only owner can view it?

@FernandoDeOliveira
Copy link
Copy Markdown

FernandoDeOliveira commented Feb 15, 2020

For this, you must edit your ViewSet. Like this exemplo, only the owner of the product can view it.

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet

from .serializers import ProductSerializer
from ..models import Product

class ProductViewSet(ModelViewSet):
    """Handles creating, reading and updating MyUsers products"""
    authentication_classes = (TokenAuthentication,)
    serializer_class = ProductSerializer
    # get all products on DB
    queryset = Product.objects.all()
    permission_classes = (IsAuthenticated, )

    def perform_create(self, serializer):
         # when a product is saved, its saved how it is the owner
        serializer.save(owner=self.request.user)

    def get_queryset(self):
        # after get all products on DB it will be filtered by its owner and return the queryset
        owner_queryset = self.queryset.filter(owner=self.request.user)
        return owner_queryset

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment