Understanding permissions in Django
I trying to understand permissions in Django. In the points below I wrote what I was able to find on this issue and how I understand it. Maybe someone will be able to tell me if I am thinking correctly or if it works in a different way. I will be grateful for additional articles on this topic. Thanks!
1. APIView with built-in permissions
Django has some built-in permissions that we can use in APIView through permission_classes.
class OrderView(APIView):
permission_classes = [permissions.IsAuthenticated]
We can add the following built-in permissions to permission_classes, because they don’t have has_object_permission:
AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly, IsAdminUser, DjangoModelPermissions, DjangoModelPermissionsOrAnonReadOnly
2. APIView with custom permissions
Let’s say that we want to use the custom permission from the point 1 in APIView. Can we use permission_classes in that case?
class OrderView(APIView):
permission_classes = [permissions.IsAuthenticatedAndOwner]
I don’t know which object will be sent to has_object_permission and how to do it. Is it a good way?
def has_object_permission(self, request, view, obj): # <-- obj
return obj.user == request.user
3. APIView with check_permissions and check_object_permissions.
I am a little confused about the methods. If I understood correctly these methods are used to call has_permission and has_object_permission from APIView? Is there a different reason to use it? Do we use it only with APIView?
4. ViewSet with custom permissions
Let’s say that we want to use the custom permission from the point 1 but with ViewSet
class MessageViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticatedAndOwner]
queryset = Message.objects.all()
serializer_class = MessageSerializer
def perform_create(self, serializer):
serializer.save(author=self.request.user)
In that case what will be sent as obj to has_object_permission?
def has_object_permission(self, request, view, obj): # <-- obj
return obj.user == request.user
Will it be data from queryset?