Object level permissions

Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.

To do that we're going to need to create a custom permission.

In the snippets app, create a new file, permissions.py

  1. from rest_framework import permissions
  2. class IsOwnerOrReadOnly(permissions.BasePermission):
  3. """
  4. Custom permission to only allow owners of an object to edit it.
  5. """
  6. def has_object_permission(self, request, view, obj):
  7. # Read permissions are allowed to any request,
  8. # so we'll always allow GET, HEAD or OPTIONS requests.
  9. if request.method in permissions.SAFE_METHODS:
  10. return True
  11. # Write permissions are only allowed to the owner of the snippet.
  12. return obj.owner == request.user

Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail view class:

  1. permission_classes = [permissions.IsAuthenticatedOrReadOnly,
  2. IsOwnerOrReadOnly]

Make sure to also import the IsOwnerOrReadOnly class.

  1. from snippets.permissions import IsOwnerOrReadOnly

Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.