Home > Back-end >  Permission for owner that user account
Permission for owner that user account

Time:06-16

I building 2 permission for the user account owner and the apartment owner. Although they have the same code, the user account owner doesn't work.

permissions.py

class IsOwnerUserOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.username == request.user # Not Work


class IsOwnerApartmentOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.seller == request.user  # Work OK

views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly, IsOwnerUserOrReadOnly]

class ApartmentViewset(viewsets.ModelViewSet):
    queryset = Apartment.objects.filter(issold=False).order_by('-timestamp')
    serializer_class = ApartmentSerializer
    # Set permission for only user owner apartment can edit it.
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly]

enter image description here enter image description here

CodePudding user response:

I think the return expression of the first permission class is not correct. It should be obj, not obj.username because request.user is the instance of the User model.

class IsOwnerUserOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj == request.user # Not Work
  • Related