sadat
sadat

Reputation: 4352

How to use PUT operation without ID in url with django

I was trying to implement a PUT method without an ID although this does not comply with REST principle. However I was just wondering if this can be done in anyway because I can easily get User instance from self.request.user. So, if I make the view

class ProfileViewSet(mixins.ListModelMixin,
                     mixins.UpdateModelMixin,
                     viewsets.GenericViewSet):
    serializer_class = UserProfileSerializer
    permission_classes = [IsAuthenticated]
    queryset = User.objects.all()
    lookup_field = 'username'

    def get_object(self):
        try:
            return User.objects.get(pk=self.request.user.id)
        except User.DoesNotExist:
            raise NotFound()

    def update(self, request, *args, **kwargs):
     ............???

Unfortunately, I could not reach the update function as it always throw an exception saying "PUT method is not allowed".

Thanks in advance.

Upvotes: 2

Views: 1261

Answers (1)

4140tm
4140tm

Reputation: 2088

Do you insist on performing the update on the same url as list and create? (sounds like this is what you are trying)

If not, you can register another action that performs the update as you want it:

#  will be accessible on <list view url>/update/
@action(methods=["PUT"], detail=False, url_path="update")
def update_current_user(self, request):
    ...

Doing it on the same url is also possible but would require some more gymnastics. At the very least you'll need to update the mapping between request methods and view methods. One way to this is described here in the docs. You might also need to remove the UpdateModelMixin.

Upvotes: 3

Related Questions