typeddjango / djangorestframework-stubs

PEP-484 stubs for django-rest-framework
MIT License
453 stars 117 forks source link

BasePermission.has_permission has wrong type? #524

Closed Leghart closed 11 months ago

Leghart commented 11 months ago

Bug report

What's wrong

I wanted to add types for this code:

class ActionPermissions(DjangoModelPermissions):
    def has_permission(self, request: Request, view: GenericViewSet) -> bool:
        if view.action == "custom_perm":
            return request.user.has_perm("actions.custom_perm")

        return super().has_permission(request, view) <-- `view` has APIView signature

after changing to make my code match your typing:

class ActionPermissions(DjangoModelPermissions):
    def has_permission(self, request: Request, view: APIView) -> bool:
        if view.action == "custom_perm":  <-- view has no attribute 'action'
            return request.user.has_perm("actions.custom_perm")

        return super().has_permission(request, view)

I made some research and found that action attribute is created in ViewSetMixin in drf. If my viewset inherits from GenericViewSet, I think I should be able to perform any operation related to the action field in the has_permission method.

My viewset looks:

class ActionViewSet(CreateModelMixin, DestroyModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
    queryset = Action.objects.all().order_by("id")
    permission_classes = (ActionPermissions,)
    serializer_class = ReadOnlyActionSerializer

How is that should be

Not sure, but maybe something with Generic type to determine exaclty incoming type?

class BasePermission(metaclass=BasePermissionMetaclass, Generic[T]):
    def has_object_permission(self, request: Request, view: T, obj: Any) -> bool: ...

or add a possible GenericViewSet type?

System information

intgr commented 11 months ago

Did you manage to solve the issue?

In case someone else stumbles on this, it could be useful to describe in a comment what was wrong and how you solved it.

Leghart commented 11 months ago

duplicate of #104