[Django]-Django rest_framework, disable authentication and permission in specific method

3👍

The action decorator allows specifying action-specific permission classes. This should do:

    @action(methods=['post'], detail=False, permission_classes=[AllowAny])
    def signup_user(self, request):
        # ...

(don’t forget importing AllowAny)

1👍

and for the default actions, i.e create , retrieve , update , partial_update , destroy and list, you can override the get_permissions method (for subclasses of rest mixins only)
i.e

def get_permissions(self):
    permission_classes = []
    if self.action =='create':
        permission_classes = [AllowAny,]
    else:
        permission_classes = [IsAuthenticated,]

    return [permission() for permission in permission_classes]

at this point, you can even validate with the http methods, ie POST, GET, PUT … by referencing self.request.

The same can be done to authentication_classes by overriding get_authenticators method

def get_authenticators(self):
    """
    Instantiates and returns the list of authenticators that this view can use.
    """
    authentication_classes = []
    if self.action !='create':
        authentication_classes = [TokenAuthentication, ]
    
    return [auth() for auth in authentication_classes]

Leave a comment