Per this issue on the DRF issues tracker, the best way seems to be to create a custom permissions class. The view object has an action
attribute that can be used to vary what you do in response to each sub-action for a ViewSet.
class IsCreationOrIsAuthenticated(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated():
if view.action == 'create':
return True
else:
return False
else:
return True
or the more detailed one from AssembledAdam
(Code copied here in line with SO policy of not just linking out, in case the link is broken or altered.)
class AnonCreateAndUpdateOwnerOnly(permissions.BasePermission):
"""
Custom permission:
- allow anonymous POST
- allow authenticated GET and PUT on *own* record
- allow all actions for staff
"""
def has_permission(self, request, view):
return view.action == 'create' or request.user and request.user.is_authenticated
def has_object_permission(self, request, view, obj):
return view.action in ['retrieve', 'update', 'partial_update'] and obj.id == request.user.id or request.user.is_staff
class ListAdminOnly(permissions.BasePermission):
"""
Custom permission to only allow access to lists for admins
"""
def has_permission(self, request, view):
return view.action != 'list' or request.user and request.user.is_staff