El Mehdi Lamrhari
El Mehdi Lamrhari

Reputation: 21

Overriding the UserDetailsSerializer in django-rest-auth

I am trying to modify the UserDetailsSerializer with a customized User Detail, but when the server is running, it throws an error of " 'User' object has no attribute 'user'". I tried a lot of methods and none of them work.

My code is:

mode.py

class userProfileModel(models.Model):

GENDER = [
    ('', ""),
    ('M', "Male"),
    ('F', "Female")
]

user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE, default='')
age = models.DateField(auto_now_add=True)
gender = models.CharField(max_length=10, choices=GENDER, default='')
phone = models.IntegerField(default=0)
user_is_active = models.BooleanField(default=False)

def __str__(self):
    return self.user.username

And serializers.py

from rest_auth.serializers import UserDetailsSerializer
from rest_framework import serializers

from .models import userProfileModel


class Profile(serializers.ModelSerializer):
    user = UserDetailsSerializer()
    class Meta:
        model = userProfileModel
        fields = ('user',)


class UserDetailsSerializer(UserDetailsSerializer):
    profile = Profile(many=True)

    class Meta(UserDetailsSerializer.Meta):
        fields = UserDetailsSerializer.Meta.fields + ('profile',)
        read_only_fields = ('',)

And settings.py

REST_AUTH_SERIALIZERS = {
'USER_DETAILS_SERIALIZER': 'app.serializers.UserDetailsSerializer',
}

When I run this code, it throws this error.

Got AttributeError when attempting to get a value for field profile on serializer UserDetailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'profile'.

Upvotes: 1

Views: 1693

Answers (1)

JPG
JPG

Reputation: 88579

use source='userprofile' as

class UserDetailsSerializer(UserDetailsSerializer):
    profile = Profile(source='userprofile')

    class Meta(UserDetailsSerializer.Meta):
        fields = UserDetailsSerializer.Meta.fields + ('profile',)
        read_only_fields = ('',)

Since User and userProfileModel in a OneToOne relation, you don't want to specify the many=True argument in the serializer

Upvotes: 1

Related Questions