尝试添加userprofile
到user
模型
使用:
django rest 框架。
rest-auth 模块
但行profile = instance.userprofile
给出错误:*** django.db.models.fields.related.RelatedObjectDoesNotExist: User has no userprofile.
遵循此处的说明
另外,不确定super
声明中发生了什么
可能的错误:
1.在语句之后instance
没有,因此语句给出错误2.需要添加到userprofile
super
profile = instance.userprofile
userprofile
UserDetailsSerializer
UserDetailsSerializer
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
如果需要,请要求更清楚。
提前致谢。