classIsOwnerOrReadOnly(permissions.BasePermission): """ 设置权限只允许创建者编辑 """ defhas_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. # 为不同的请求设置权限,GET, HEAD or OPTIONS 为安全请求 if request.method in permissions.SAFE_METHODS: returnTrue
# Write permissions are only allowed to the owner of the snippet. # 写权限只有代码拥有者有,判断拥有者和请求者是否是同一个用户 return obj.owner == request.user
然后在SnippetDetail视图类中,设置权限类
1 2 3
from snippets.permissions import IsOwnerOrReadOnly permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)