首页 > 解决方案 > self.action is None in DRF

问题描述

self.action is None in get_permissions() method.
When a url is called that doesn't exist DRF doesn't throw 404 error. that's why somehow action is None in get_permissions() method.

Here is the ModelViewSet:

class UserViewSet(ModelViewSet):
    serializer_classes = {
        "list": UserSerializer,
        "retrieve": UserSerializer,
        "create": UserSerializer,
        "update": UserUpdateSerializer,
    }
    http_method_names = ["get", "post", "put"]

    def get_serializer_class(self):
        return self.serializer_classes[self.action]

    def get_permissions(self):
        if self.action is None:
            # here error raises when i call '.../accounts/blablabla/` endpoint in post request instead of 404?
            raise AssertionError("self.action cannot be None") 
        if self.action in ["list", "retrieve"]:
            return [IsAuthenticated(), IsAdmin()]
        else:
            return [AllowAny()]

Here is my discussion link #8199 in github.

标签: pythondjangodjango-rest-framework

解决方案


推荐阅读