In my views, queryset is returning all the users when I want it to be only returning the user that is currently logged. I have a get self method which has the serializer set to the user but it is not being used. When I tried get_queryset, self.request.user still doesn't return the user.
views.py:
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rsm_app.api.v1 import serializer as serializers
from rsm_app.users.models import User
class CurrentUserView(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.UserSerializer
#queryset = User.objects.filter(name=request.user.name)
def get_queryset(self):
return self.request.user
def put(self, request):
serializer = serializers.UserSerializer(
request.user, data=request.data)
if request.data and serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
Url.py:
from rest_framework import routers
from django.urls import path, re_path, include
from graphene_django.views import GraphQLView
from rsm_app.api.v1 import views
app_name = "api.v1"
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r"user", views.CurrentUserView, basename="user")
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path("graphql", GraphQLView.as_view(graphiql=True)),
re_path(r"^", include(router.urls)),
re_path(r"user/", views.CurrentUserView, name='user'),
re_path(r"^api-auth/", include("rest_framework.urls",
namespace="rest_framework")),
]
CodePudding user response:
They mentioned in the docs that you could access the current user by user = self.get_object()
You could see the full example from the official docs.
CodePudding user response:
Can you try with:
queryset = User.objects.filter(name=request.user.name).first()
or
queryset = User.objects.get(name=request.user.name)