You must be signed in to star a gist
IsOwner - Custom django-rest-framework permission to only allow owners of an object to edit it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
|from rest_framework import permissions|
|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|
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
How do I restrict permissions to only owner can view it?