Skip to content

Instantly share code, notes, and snippets.

Created April 17, 2015 08:24
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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
Copy link

MaggieChege commented Feb 2, 2019

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

Copy link

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

    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