/ rest-auth / user /处的RelatedObjectDoesNotExist:用户没有用户配置文件

时间:2018-12-21 13:25:22

标签: python django django-rest-framework django-rest-auth

我正在尝试更新UserDetailsS​​erializer,问题是当我在测试模型中运行代码时它可以工作,但是当我在实际应用中使用它时,它将引发此错误:'User'对象没有属性'userprofile'< / p>

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)

错误:

  

/ rest-auth / user /

处的RelatedObjectDoesNotExist      

用户没有用户个人资料。

2 个答案:

答案 0 :(得分:0)

这是因为尚未创建用户的UserProfile实例。您可以在post_save模型的User上使用信号,以便每当保存用户时,检查是否已为其创建UserProfile实例,如果没有,则创建一个。如下所示:

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

post_save.connect(create_profile,sender=User)

就像我的朋友在注释中建议的那样,请始终检查userProfile实例是否与hasattr(instance, 'profile')存在,如果不存在,则为该用户创建一个默认实例。

参考:这是一个很酷的话题Extending user model

答案 1 :(得分:0)

创建用户个人资料时,请确保将其保存,然后可以引用此代码段。

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()

也不要忘记导入post_save