So I'm writing my first project with DRF and I'm having some issues with setting up permissions for my viewsets. I already have authentication working with djangorestframework-jwt. Currently, I have a few different ViewSets defined. What I would like to do is allow the owner of a model object to make any changes they would like to that object, but prevent everyone else (aside admins) from even viewing the objects. Basically, I need a way of applying permission classes to specific methods to allow only admins to view 'list', owners to 'update, destroy, etc' and authenticated users to 'create'. Currently I have something like this:
class LinkViewSet(viewsets.ModelViewSet):
queryset = Link.objects.all()
serializer_class = LinkSerializer
with a model of
class Link(models.Model):
name = models.CharField(max_length=200)
url = models.URLField()
# another model with a OneToMany relationship
section = models.ForeignKey('homepage.LinkSection', related_name='links', on_delete=models.CASCADE
owner = models.ForeignKey('homepage.UserProfile'), related_name='links', on_delete=models.CASCADE)
and the permissions class I want to apply
class IsOwner(permissions.BasePermission):
def has_object_permissions(self, request, view, obj):
return obj.owner == request.user.userprofile
I'm sure it's possible to achieve this by writing completely custom views but I have a gut feeling that there is an easier way to do this especially since this is basically the last thing I have to do to finish the API. Thanks for any help and let me know if you need any more info.