【发布时间】:2017-03-09 04:18:37
【问题描述】:
尝试将userprofile 添加到user 模型
使用:
django rest 框架。
rest-auth 模块
但是profile = instance.userprofile 行给出 error:*** django.db.models.fields.related.RelatedObjectDoesNotExist: User has no userprofile.
遵循here的指示
另外,不确定super 声明中发生了什么
可能的错误:
1.instance 在super 语句之后没有userprofile,因此profile = instance.userprofile 语句给出错误
2.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
如果需要,请务必要求更清楚。
提前致谢。
【问题讨论】:
-
答案不会立即出现。而您正在尝试更新一个不存在的配置文件对象。
-
是的,我明白。这就是为什么,我想知道如何将这个
userprofile添加到UserDetailsSerializer中。我修改了问题here
标签: django-rest-framework user-profile django-serializer