[英]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' 我正在尝试更新UserDetailsSerializer,问题是当我在测试模型中运行代码时它可以工作,但是当我在实际应用中使用它时,它将引发此错误:'User'对象没有属性'userprofile'
model.py 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 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/
/ rest-auth / user /中的RelatedObjectDoesNotExist
User has no userprofile.
用户没有用户个人资料。
It's because UserProfile
instance for user is not created yet. 这是因为尚未为用户创建
UserProfile
实例。 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. 您可以在
User
模型的post_save
上使用信号,以便每当保存用户时,检查是否为其创建了UserProfile
实例,如果没有,则创建一个。 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. 就像我的朋友在注释中建议的一样,始终检查是否有
hasattr(instance, 'profile')
存在userProfile实例,如果不存在,则为该用户创建一个默认hasattr(instance, 'profile')
。
Reference: This is a cool topic Extending user model 参考:这是一个很酷的主题, 扩展用户模型
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
. 并且也不要忘记导入
post_save
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.