Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to update UserProfile connected through one-to-one field with CustomUser model in django, using django_rest_auth and django rest framework ?? #630

Open
mnamegaurav opened this issue Oct 20, 2020 · 0 comments

Comments

@mnamegaurav
Copy link

I am using dj_rest_auth which is forked from django_rest_auth with djangorestframework. I want to update the UserProfile from the same API ,where I create user.

This is my CustomUser model-

class User(AbstractUser):
    email = models.EmailField(unique=True)
    full_name = models.CharField(max_length=150, verbose_name='Full name')
    date_updated = models.DateTimeField(auto_now=True)

    username = None
    first_name = None
    last_name = None
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

This is my UserProfile model-

class UserProfile(models.Model):
    user = models.OneToOneField(User , related_name='user_profile', on_delete=models.PROTECT)
    profile_picture = models.CharField(max_length=400, null=True, blank=True)
    contact = models.CharField(max_length=20, unique=True)
    dob = models.DateField()
    age_group = models.ForeignKey(AgeGroup, on_delete=models.PROTECT)
    profession = models.ForeignKey(Profession, on_delete=models.PROTECT)
    interested_in = models.ManyToManyField(Interest)
    is_married = models.BooleanField(default=False)
    country = models.ForeignKey(Country, on_delete=models.PROTECT)
    state = models.ForeignKey(State, on_delete=models.PROTECT)
    city = models.ForeignKey(City, on_delete=models.PROTECT)
    is_profile_completed = models.BooleanField(default=False)
    date_added = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'user_profile'

    def __str__(self):
        return str(self.user.email)

    def clean(self):
        # Don't allow people less than 18
        age_in_days = (datetime.date.today() - self.dob).days
        print(age_in_days)
        age = age_in_days / 365
        print(age)
        if age < 18:
            raise ValidationError(gettext_lazy('You should be an adult (18+).'))

This is my UserSerializer-

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['pk', 'full_name', 'email', 'is_superuser', 'is_staff', 'is_active',]
        read_only_fields = ('email', 'is_superuser', 'is_staff', 'is_staff')

This is my UserProfileSerializer-

class UserProfileSerializer(UserSerializer):
    contact = serializers.CharField(source="user_profile.contact")
  
    class Meta(UserSerializer.Meta):
        fields = UserSerializer.Meta.fields + ['contact']

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('user_profile', {})

        contact = profile_data.get('contact')
        instance = super(UserSerializer, self).update(instance, validated_data)

        # get and update user profile
        # yet to write complete code
        profile = instance.user_profileer
        if profile_data and contact:
            profile.contact = contact
            profile.save()
        return instance

I have also defined REST_AUTH_SERIALIZERS for 'USER_DETAILS_SERIALIZER'

'USER_DETAILS_SERIALIZER': 'api.serializers.UserProfileSerializer',
It is giving me same error again and again, Please help me out.

AttributeError at /api/rest-auth/user/
Got AttributeError when attempting to get a value for field `user` on serializer `UserProfileSerializer`.
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 'user'.
Request Method: GET
Request URL:    http://localhost:8000/api/rest-auth/user/
Django Version: 3.1.1
Exception Type: AttributeError
Exception Value:    
Got AttributeError when attempting to get a value for field `user` on serializer `UserProfileSerializer`.
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 'user'.
Exception Location: /home/gaurav/brandlogist/honest_conversations/env/lib/python3.8/site-packages/rest_framework/fields.py, line 487, in get_attribute
Python Executable:  /home/gaurav/brandlogist/honest_conversations/env/bin/python
Python Version: 3.8.6
Python Path:    
['/home/gaurav/brandlogist/honest_conversations/brandlogist',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/gaurav/brandlogist/honest_conversations/env/lib/python3.8/site-packages']
Server time:    Tue, 20 Oct 2020 13:32:50 +0000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant