JSRB
JSRB

Reputation: 2613

DRF endpoint returns weirdly serialized object although it is fetch correctly in the view

So I'm using Django REST auth and dj-rest-auth as authentication backend for my React app. In the view it seems that it grabs the correct instance of the logged in user, but it doesn't reflect that in the response. Also if I print fields of that instance it returns the wrong data, the serializer instance however looks like it holds the correct object to serialize...hm

# views.py

class UserDetail(APIView):
    """
    Retrieve a User instance
    """
    def get(self, request):
        print('Header Token: ' + str(request.META['HTTP_AUTHORIZATION']))
        print('request.user: ' + str(request.user))
        try:
            user_profile = UserProfile(user=request.user)
            print('user_profile: ' + str(user_profile))
            print('user_profile.company: ' + str(user_profile.company)). # Why is this none?
            serializer = UserProfileSerializer(user_profile)
            print('serializer: ' + str(serializer)) # looks like the instance is correct though..
            print('serializer.data: ' + str(serializer.data))
            return Response(serializer.data)
        except UserProfile.DoesNotExist:
            raise Http404

Returns

enter image description here

and Postman returns

https://i.sstatic.net/vzkZ2.png

But the data should be:

enter image description here

# models.py

class UserProfile(models.Model):
    """
    Extends Base User via 1-1 for profile information
    """
    # Relations
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True)

    # Roles
    is_ta = models.BooleanField(default=False)  # indicates if user is part of TA department

    def __str__(self):
        return F'{self.user.first_name} {self.user.last_name}'


@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    instance.userprofile.save()
# serializers.py

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'

Upvotes: 0

Views: 28

Answers (1)

Ersain
Ersain

Reputation: 1520

You are incorrectly fetching the UserProfile instance, instead of:

user_profile = UserProfile(user=request.user)

try:

user_profile = UserProfile.objects.get(user=request.user)

UPD: In order to create a nested representation either set depth attribute in Meta of your serializer:

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'
        depth = 1

or create a separate serializer for your related fields, e.g.:

class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = your_fields

and set the serializer as field:

class UserProfileSerializer(serializers.ModelSerializer):
    company = CompanySerializer()

    class Meta:
        model = UserProfile
        fields = '__all__'

Upvotes: 1

Related Questions