使用推荐方法

时间:2016-11-06 15:29:30

标签: django-rest-auth

我正在使用推荐方法here向用户添加字段。 #3如何更新分配给用户模型的UserProfile?

当我尝试在/ rest-auth / user / url上保存邮政编码时,我得到例外情况“用户没有用户配置文件。”

模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    # custom fields for user
    zip_code = models.CharField(max_length=5)

串行器:

class UserSerializer(UserDetailsSerializer):
zip_code = serializers.CharField(source="userprofile.zip_code")

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

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

    instance = super(UserSerializer, self).update(instance, validated_data)

    # get and update user profile
    profile = instance.userprofile
    if profile_data and zip_code:
        profile.zip_code = zip_code
        profile.save()
    return instance

提前感谢!

0 个答案:

没有答案
相关问题