3

I user Django Rest Framwork. I want to make a api for delete an object like this

DELETE .../items/

to delete request.user's item. (Each user can create at most one item only, and only owner can delete his item.)

I use mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet for list view and create. I have tried

@action(methods=['delete'], detail=False, url_path='')
    def leave(self, request, *args, **kwargs):
     ...

but url pattern will go:

.../items/leave/$

How can I config the router or path for this? Thanks

Kermit
  • 4,922
  • 4
  • 42
  • 74
  • Can you show your view class? – JPG Jul 02 '18 at 04:17
  • Could you show your current urls? If you're already using a router for the view you don't really need to add anything. Since you specify `@action(detail=False)` the expected url will be the same as your list url, but with '/leave' at the end. – gdvalderrama Apr 14 '21 at 13:14

2 Answers2

0

In Django rest framework decorators, if url_path be empty strig that replace by function name. So you cannot use url_path='' as a URL path.

-1

You can use just a simple APIView with GET method, and do what you want in that. like this:

class MyDeleteAPIView(APIView):

    def get(self, request, *args, **kwargs):
        # for example
        try:
            user = request.user
            instance = SomeModel.objects.get(user=user)
            instance.delete()
            return Response({"message":"deleted successfuly"}, status=status.HTTP_200_OK)
        except:
            return Response({"message":"delete fail"}, status=status.HTTP_400_BAD_REQUEST)

now you can define your desired url:

path('delete/', MyDeleteAPIView.as_view(), name='delete'),
Ali
  • 2,541
  • 2
  • 17
  • 31
  • 1
    I'm sorry but I want api like this: DELETE '.../items/' will delete request.user's item where GET '.../items/' will return a list view, instead of an api 'delete..., or leave' – Bách Đoàn Việt Jul 01 '18 at 12:20
  • No, you can customize GET method and instead return a list, do delete process. It is not professional. But sometimes you need do like this – Ali Jul 01 '18 at 16:09