如何撰写IsThePhysicalServerUser
?
你看到了UpdateAPIView
:
class PhysicalServerCustomerUpdateAPIView(UpdateAPIView):
"""
Customer's update PhysicalServer
"""
serializer_class = CustomerUpdatePhysicalServerSerializer
permission_classes = [IsThePhysicalServerUser]
queryset = PhysicalServer.objects.all()
我想写一个IsThePhysicalServerUser
的权限。
PhysicalServer
模型如下:
class PhysicalServer(models.Model):
"""
实体服务器
"""
name = models.CharField(max_length=32)
desc = models.CharField(max_length=256, null=True, blank=True)
...
user = models.ForeignKey(to=User, related_name="physical_servers", null=True, blank=True, on_delete=models.SET_NULL)
我希望IsThePhysicalServerUser
权限实现PhysicalServer实例的使用是请求用户。如何写权限?
答案 0 :(得分:0)
只需检查实例的用户等于request.user
:
class IsSuperAdminOrPhysicalServerCustomer(permissions.BasePermission):
"""
SuperUser or instance.user equals request.user
"""
def has_object_permission(self, request, view, obj):
# if you want everyone can see user info
if request.method in permissions.SAFE_METHODS:
return True
# if you use Django2.0 is_authenticated(request.user) should be changed to request.user.is_authenticated
if request.user and request.user.is_authenticated:
# instance.user equal self or is superuser
return obj.user == request.user or request.user.is_superuser
else:
return False