[Django]-How to add custom permission in viewset

4๐Ÿ‘

I canโ€™t use a decorator like: @permission_classes(IsAuthenticated, ) in extra actions within ViewSet

To use different permissions in actions, instead, put it into the @action() as a parameter.

@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
    def set_password(self, request, pk=None):
       ...

drf doc

๐Ÿ‘คC.K.

1๐Ÿ‘

simply create a custom permission class

class FixAnAppointmentPermssion(permissions.BasePermission):
    def has_permission(self, request, view):
        return True or False

then the in your view set class use your custom permission

class settingsViewSet(viewsets.ModelViewSet):
    serializer_class = SettingsSerializer
    queryset = Setting.objects.all()
    permission_classes = (FixAnAppointmentPermssion,)
๐Ÿ‘คaliva

1๐Ÿ‘

by docs custom-permissions, list of view actions actions
my_permissions.py

from rest_framework import permissions

class FixPermission(permissions.BasePermission):
    """
    fix_an_appointment
    """

    def has_permission(self, request, view):
        if request.user.is_authenticated :
            if view.action == 'retrieve':
                return request.user.has_perms('fix_list_perm')
            if view.action == 'retrieve':
                return request.user.has_perms('fix_an_appointment')
        return False

in views.py

from my_permissions import FixPermission


class settingsViewSet(viewsets.ModelViewSet):
    serializer_class = SettingsSerializer
    queryset = Setting.objects.all()
    permission_classes = (FixPermission,)
๐Ÿ‘คBrown Bear

0๐Ÿ‘

We can set permission for each functions like create, retrive, update, delete(add,edit,delete and update)

from my_permissions import FixPermission

class FixAnAppointmentPermssion(permissions.BasePermission):
    def has_permission(self, request, view):
       return True or False

class YourViewSet(viewsets.ModelViewSet):
serializer_class = SettingsSerializer
queryset = Your.objects.all()

@permission_classes(FixAnAppointmentPermssion,)
def create(request, format=None):
  content = {
           'status': 'request was permitted'
  }
return Response(content)

@permission_classes(FixAnAppointmentPermssion,)
def retrive(request, format=None):
  content = {
           'status': 'request was permitted'
  }
return Response(content)
๐Ÿ‘คRamesh K

Leave a comment