Django Rest Framework: @Action Route with same url_path as Viewset

1.6k views Asked by At

I want to POST to a DRF Viewset Detail Route. Is this possible? I know with DRF you can override the Create field, but this won't allow you to access the detail route.

Specifically in this example I want the design of the route to be POST /foo/<pk>/, and not some route like POST /foo/<pk>/bar/.

Here's what I want to accomplish, notice the IS_THERE_A_WAY_TO_DO_THIS:

class FooViewSet(
    mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet
):
    """
    Foo-related viewsets.
    """

    permission_classes = [IsAuthenticated]
    queryset = models.Foo.objects.all()
    serializer_class = serializers.FooSerializer

    @action(
        methods=["post"],
        detail=True,
        permission_classes=[IsAuthenticated],
        url_path="", <-- IS_THERE_A_WAY_TO_DO_THIS? Normally this wont work.
        url_name="foobar",
    )
    def foobar_process(self, request, pk=None):
        pass

urls.py

router = DefaultRouter()
...
router.register(r"foo", FooViewSet, basename="foo")
...

urlpatterns += [
    re_path(r"^", include(router.urls)),
]

0

There are 0 answers