Home > Net >  How to retrive data from OneToOne Relational Model in DRF using API view
How to retrive data from OneToOne Relational Model in DRF using API view

Time:07-28

I have imported User model and customized it a/c to my need and make OneToOne Relation with UserProfileModel Model. While retrieving data I got this error. "The serializer field might be named incorrectly and not match any attribute or key on the AnonymousUser instance. Original exception text was: 'AnonymousUser' object has no attribute 'gender'."

My Model is :

class UserProfileModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='userprofilemodel')
    gender = models.CharField(max_length=20)
    locality = models.CharField(max_length=70)
    city = models.CharField(max_length=70)
    address = models.TextField(max_length=300)
    pin = models.IntegerField()
    state = models.CharField(max_length=70)
    profile_image = models.FileField(upload_to='user_profile_image', blank=True)

My Serializer looks like:

class UserProfileSerializer(serializers.ModelSerializer):

class Meta: 
    model= User 
    fields = ['id', 'name' , 'email','mobile',]

class UserProfileModelSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(many=True, read_only=True)
    class Meta: 
        model= UserProfileModel 
        fields = ['user','gender' , 'locality','city','address','pin','state','profile_image', ]

My view looks like: class UserProfileDataView(APIView):

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

I want to retrieve profile data of the logged user using UserProfileModel Model

CodePudding user response:

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_200_OK)

CodePudding user response:

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]
  • Related