问题
Trying to add userprofile
to user
model
using:
django rest framework.
rest-auth module
But line profile = instance.userprofile
giving error:*** django.db.models.fields.related.RelatedObjectDoesNotExist: User has no userprofile.
following instructions from here
Also, not sure on what is happening in super
statement
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
Do ask for more clarity if required.
Thanks in advance.
回答1:
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:
来源:https://stackoverflow.com/questions/32542220/how-to-add-userprofile-to-userdetailsserializer-in-django