问题描述
试图将用户个人资料
添加到用户
模型
使用:
django rest框架。
rest-auth模块
但是行 profile = instance.userprofile
给出了错误:
*** django.db.models.fields.related.RelatedObjectDoesNotExist:用户没有用户个人资料。
按照 中的说明进行操作
following instructions from here
此外,不确定 super
语句中发生了什么
Also, not sure on what is happening in super
statement
可能的错误:
1。实例
没有用户个人资料
在 super
语句之后,因此
profile = instance.userprofile
语句给出错误
2. 用户配置文件
需要添加到 UserDetailsSerializer
Possible errors:
1.instance
is not having userprofile
after the super
statement, hence profile = instance.userprofile
statement giving error
2.userprofile
needs to be added to UserDetailsSerializer
UserDetailsSerializer
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('username', 'email', 'first_name', 'last_name')
read_only_fields = ('email', )
UserSerializer
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
如果需要,请要求更清楚。
预先感谢。 / p>
Do ask for more clarity if required.
Thanks in advance.
推荐答案
在,假定已经创建了用户个人资料,现在可以对其进行更新。您只需要一张支票
In the documentation it is assumed that userprofile was already created and now can be updated. You just need a check
# get and update user profile
try:
profile = instance.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile()
if profile_data and company_name:
这篇关于如何在Django中将用户配置文件添加到UserDetailsSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!