[Django]-DRF : parameter in custom permission class with function based views

6👍

permission_classes must be passed a list of permission classes, not instances of permissions. One way to dynamically create permission classes would be to create a method that returns a dynamically created class using type

from rest_framework import permissions


class HasPermissionBase(permissions.BasePermission):
    """
    Allows access only to users who have the appropriate permission.
    """

    permission_codename = ""

    def has_permission(self, request, view):
        return request.user.has_permission(self.permission_codename)


def HasPermission(permission_codename):
    return type('HasPermission', (HasPermissionBase, ), {'permission_codename': permission_codename})

Or you could override the __call__ method on your custom permission and return self so that it acts like a class when called



class HasPermission(permissions.BasePermission):
    """
    Allows access only to users who have the appropriate permission.
    """

    permission_codename = ""

    def __init__(self, permission_codename):
        super().__init__()
        self.permission_codename = permission_codename

    def __call__(self):
        return self

    def has_permission(self, request, view):
        return request.user.has_permission(self.permission_codename)

Leave a comment