0

In the docs, it says that the below given way can be used to give custom permissions.The has_perm decorator is used to check user permissions. But it does not say where these permissions are defined or what they do. Do i not need to define them ? If yes where and how do i do it? Thanks for all the helps.

class Task(models.Model):
    ...
    class Meta:
        permissions = (
        ("view_task", "Can see available tasks"),
        ("change_task_status", "Can change the status of tasks"),
        ("close_task", "Can remove a task by setting its status as closed"),
    )
SayYes
  • 1
  • 3

1 Answers1

0

You can create the custom permission class, I have done that below.

class BaseModelPerm(permissions.DjangoModelPermissions):

    def get_custom_perms(self, method, view):
        app_name = view.model._meta.app_label
        if hasattr(view, 'extra_perms_map'):
            return [app_name+"."+perms for perms in view.extra_perms_map.get(method, [])]
        else:
            return []

    def has_permission(self, request, view):
        perms = self.get_required_permissions(request.method, view.model)
        perms.extend(self.get_custom_perms(request.method, view))
        return (
            request.user and
            (request.user.is_authenticated() or not self.authenticated_users_only) and
            request.user.has_perms(perms)
        )

Above permission can user in any view like below

class UserView(viewsets.ModelViewSet):
    """ User model view for the admin user """
    model = User
    permission_classes = (
      permissions.IsAuthenticated,
      accounts_permissions.IsStaffOrVendor,
      accounts_permissions.BaseModelPerm,
    )
    extra_perms_map = {
      'GET': ["can_view_user"]
    }

extra_perms_map is dict of permission related to that method.

aman kumar
  • 3,086
  • 1
  • 17
  • 24