Reputation: 511
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
...
Upvotes: 6
Views: 4262
Reputation: 3526
In my project, I am using both plain Django and Django-rest-framework and I am using request.user
as below.
class ProfileRunCounts(generics.ListCreateAPIView):
def get(self, request, *args, **kwargs):
id = self.request.user
update after comments.
HttpRequest.user
From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of AnonymousUser.REST framework's Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication.
APIView classes are different from regular View classes in the following ways:
Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.
With above extract from the documentation I believe user object is always available in request.
Sometimes it is in self.request.user
and sometimes it is in request.user
.
Upvotes: 0
Reputation: 10806
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()),
Upvotes: 9