Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and Postman returns

https://i.stack.imgur.com/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__'

>Solution :

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__'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading