Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rest-framework @detail_route without pk

In rest framework exists some way to use session user instead pk and self.get_object() in a @detail_route view?

I want to use request.user and don't send pk in the url.

Or maybe use another decorator instead @detail_route...

like image 949
Rodolpho Pivetta Sabino Avatar asked Mar 12 '23 03:03

Rodolpho Pivetta Sabino


1 Answers

It's hard to tell what you're trying to archive in the first place. Maybe it's easier to use a separate view instead of the viewset action this case? For example here is a view snippet that lets currently logged in user manage his account:

class CurrentUser(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user

    def perform_destroy(self, instance):
        instance.is_active = False
        instance.save()

Add this to your urlpatterns without pk in the pattern:

    url(r'^users/me/$', CurrentUser.as_view()),
like image 73
Igonato Avatar answered Mar 24 '23 23:03

Igonato