根据DRF 问题跟踪器上的这个问题,最好的方法似乎是创建自定义权限类。视图对象有一个action
属性,可用于改变您为响应 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
或更详细的来自AssembledAdam
(此处复制的代码符合不只是链接出去的 SO 政策,以防链接被破坏或更改。)
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