【问题标题】:How to add userprofile to UserDetailsSerializer in django如何在 django 中将用户配置文件添加到 UserDetailsS​​erializer
【发布时间】: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.instancesuper 语句之后没有userprofile,因此
profile = instance.userprofile 语句给出错误
2.userprofile 需要添加到UserDetailsSerializer

UserDetailsS​​erializer

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


【解决方案1】:

documentation 中假定用户配置文件已经创建并且现在可以更新。你只需要一张支票

# get and update user profile
    try:
        profile = instance.userprofile
    except UserProfile.DoesNotExist:
        profile = UserProfile()
    if profile_data and company_name:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2012-07-07
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多