python - 如何使用 django 和 rest 框架更新用户数据?

标签 python django django-rest-framework

尝试更新用户时出现以下消息:“具有此用户名的用户已存在”

我有一个标准的 Django 用户模型和另一个扩展的配置文件模板。

如何更新此数据,包括用户个人资料。

谢谢。

模型

class Profile(User):
    nome_empresa = models.CharField(max_length=200)
    cnpj = models.CharField(max_length=15)

    def __str__(self):
        return self.nome_empresa

序列化器

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('nome_empresa', 'cnpj')


class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'profile')

查看

class usuario(APIView):


    def patch(self, request, format=None):

        user = UserSerializer(data=request.data)

        if user.is_valid():
            user.update(instance=request.user)
            return Response(HTTP_200_OK)

        return Response(user.errors)

最佳答案

django-rest-framework 默认不更新嵌套序列化器。要更新配置文件对象,您需要重写序列化程序的更新方法。

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    def update(self, instance, validated_data):
        """Override update method because we need to update
        nested serializer for profile
        """
        if validated_data.get('profile'):
            profile_data = validated_data.get('profile')
            profile_serializer = ProfileSerializer(data=profile_data)

            if profile_serializer.is_valid():
                profile = profile_serializer.update(instance=instance.profile)
                validated_data['profile'] = profile

        return super(UserSerializer, self).update(instance, validated_data)

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'profile')

关于python - 如何使用 django 和 rest 框架更新用户数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46061406/

相关文章:

python - 变分自动编码器 (VAE) 显示不一致的输出

Python:如何将区域保持在 canny close edge 的区域内

python - Django Rest框架全局分页参数不适用于ModelViewSet

django - 通过 Django 后端和 Angular 前端删除 MongoDB 集合中的所有文档

html - 在 html 中使用 django 的 if 语句有多安全?

Django REST框架: Per-user throttles

Python lxml : insert text at given position relatively to subelements

python - python导入是否保证按顺序排列?依靠这个是个好主意吗?

Django 页面未在 Facebook iframe 中呈现

django - 检查多对多关系或属性