中将用户配置文件添加到UserDetailsS​​erializ

中将用户配置文件添加到UserDetailsS​​erializ

本文介绍了如何在Django中将用户配置文件添加到UserDetailsS​​erializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图将用户个人资料添加到用户模型

使用
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. 用户配置文件需要添加到 UserDetailsS​​erializer

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

UserDetailsS​​erializer

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中将用户配置文件添加到UserDetailsS​​erializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:10