How to add userprofile to UserDetailsSerializer in django

ぐ巨炮叔叔 提交于 2019-12-08 09:43:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!