El Mehdi Lamrhari
El Mehdi Lamrhari

Reputation: 21

RelatedObjectDoesNotExist at /rest-auth/user/: User has no userprofile

I am trying to update UserDetailsSerializer and the problem is when I run my code in my test model it works but when I use it in my actual app, it throws this error: 'User' object has no attribute 'userprofile'

model.py

class userProfileModel(models.Model):

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

   user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile', default='')
   avatar = models.ImageField(upload_to='avatar/', default='avatar/no-avatar.png')
   age = models.DateField(auto_now_add=True)
   gender = models.CharField(max_length=10, choices=GENDER, default='')
   address = models.CharField(max_length=500, default='')
   longitude = models.FloatField(default=0.0)
   latitude = models.FloatField(default=0.0)
   phone = models.IntegerField(default=0)
   user_is_active = models.BooleanField(default=False)

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

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = userProfileModel
        fields = (
            'id',
            'avatar',
            'age',
            'gender',
            'address',
            'longitude',
            'latitude',
            'phone',
        )

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

    def update(self, instance, validated_data):
        # User data
        nested_serializer = self.fields['profile']
        nested_instance = instance.userprofile
        nested_data = validated_data.pop('userprofile')
        nested_serializer.update(nested_instance, nested_data)
        return super(UserDetailsSerializer, self).update(instance, validated_data)

The error:

RelatedObjectDoesNotExist at /rest-auth/user/

User has no userprofile.

Upvotes: 0

Views: 1060

Answers (2)

Bidhan Majhi
Bidhan Majhi

Reputation: 1370

When you are creating user profile, make sure you save them, you can refer this snippet.

class Profile(models.Model):
    # ...

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
     instance.profile.save()

And also don't forget to import post_save.

Upvotes: 0

Reza Torkaman Ahmadi
Reza Torkaman Ahmadi

Reputation: 3038

It's because UserProfile instance for user is not created yet. You can use a signal on post_save of User model, so that whenever user is saved, check if UserProfile instance for it is created, if not then create one. like below:

def create_profile(sender,**kwargs ):
    if kwargs['created']:
        user_profile=UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile,sender=User)

Also like my friend suggested in comments, Always check if userProfile instance is exist with hasattr(instance, 'profile'), if not then create a default one for that user.

Reference: This is a cool topic Extending user model

Upvotes: 1

Related Questions