Home > OS >  How to set permissions for CRUD operations in ModelViewSet Django
How to set permissions for CRUD operations in ModelViewSet Django

Time:05-27

I have a viewset for model News.

I want to do next permissions: All people can see news. Only authorized users and admin can create news. Only owner and admin can update news. Only admin can delete news.

How can I set different permissions for each operation? For create I want to use: IsAuthenticated and IsAdminUser. For update I want to use IsAdminUser and I create my own permission for owner. For delete I want to use also IsAdminUser.

view:

class NewsViewSet(viewsets.ModelViewSet):
    queryset = News.objects.all()
    serializer_class = NewsSerializer

permission:

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True

        return obj.author == request.user

CodePudding user response:

class Viewset(BaseModelViewSet):enter code here
queryset = Model.objects.all()
serializer_class = ModelSerializer
permission_classes_by_action = {
    'create': (permissions.IsAdminUser,),
    'list': (permissions.IsAuthenticatedOrReadOnly,),
    'retrieve': (permissions.AllowAny,),
    'update': (permissions.AllowAny,),
    'destroy': (permissions.IsAdminUser,),
    'search': (permissions.IsAuthenticated,)  

Like this you can use the pre-built permission or create custom permission class

  • Related