如何写一个实例用户的权限是request.user?

时间:2018-06-06 12:19:18

标签: python django django-rest-framework

如何撰写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实例的使用是请求用户。如何写权限?

1 个答案:

答案 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