0

尝试添加userprofileuser模型

使用
django rest 框架。
rest-auth 模块

但行profile = instance.userprofile给出错误
*** django.db.models.fields.related.RelatedObjectDoesNotExist: User has no userprofile.

遵循此处的说明

另外,不确定super声明中发生了什么

可能的错误:
1.在语句之后instance没有,因此语句给出错误2.需要添加到userprofilesuper
profile = instance.userprofile
userprofileUserDetailsSerializer

UserDetailsS​​erializer

class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('username', 'email', 'first_name', 'last_name')
        read_only_fields = ('email', )

用户序列化器

class UserSerializer(UserDetailsSerializer):

    company_name = serializers.CharField(source="userprofile.company_name")

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

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

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

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

如果需要,请要求更清楚。
提前致谢。

4

1 回答 1

0

文档中假定用户配置文件已经创建并且现在可以更新。你只需要一张支票

# get and update user profile
    try:
        profile = instance.userprofile
    except UserProfile.DoesNotExist:
        profile = UserProfile()
    if profile_data and company_name:
于 2017-03-08T20:18:37.200 回答