Skip to content

Instantly share code, notes, and snippets.

@Kobold
Created April 17, 2015 08:24
Show Gist options
  • Save Kobold/c5ead2b72b2be03eb0ca to your computer and use it in GitHub Desktop.
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
@FernandoDeOliveira
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
        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