[Answered ]-How to retrive data from OneToOne Relational Model in DRF using API view

1👍

Your first issue in that you are passing a User instance to the UserProfileModelSerializer, which is expecting a UserProfileModel instance. To fix this you need to change:

serializer = UserProfileModelSerializer(request.user)

to

serializer = UserProfileModelSerializer(request.user.userprofilemodel)

where userprofilemodel is the related_name you have set on the user field in your UserProfileModel.

Second issue is, as Mohamed Beltagy said, you’re allowing anyone to access the view, including unauthenticated users. Django rest framework has a built in mixin that you can use to restrict access to authenticated users only (https://www.django-rest-framework.org/api-guide/permissions/#isauthenticated).

from rest_framework.permissions import IsAuthenticated


class UserProfileDataView(APIView):
    permission_classes = [IsAuthenticated]

0👍

the problem here is you are passing an anonymous user which has no profile ( you permit non-authenticated users access this view)

def get(self, request, format=None):
    # user = UserProfileModel.objects.all()
    if request.user.is_authenticated:
        serializer = UserProfileModelSerializer(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK)
    else:
        return Response(status=status.HTTP_401_UNAUTHORIZED)

Leave a comment