在 Django REST Framework 中隐藏 GET 中的密码字段,但不隐藏 POST 中的密码字段,其中序列化程序中的深度 = 1

2024-01-08

我有 2 个模型:User 和 UserSummary。 UserSummary 有一个 User 的外键。我刚刚注意到如果我设置depth= 1 within UserSummarySerializer,密码字段包含在输出中。它已被散列,但最好仍然排除该字段。

为了隐藏密码字段,我只是在序列化器中显式设置用户字段,如下所示:

class UserSerializer(serializers.ModelSerializer):
    """A serializer for our user profile objects."""

    class Meta:
        model = models.User
       extra_kwargs = {'password': {'write_only': True}}
        exclude = ('groups', 'last_login', 'is_superuser', 'user_permissions', 'created_at')

    def create(self, validated_data):
        """Create and return a new user."""

        user = models.User(
            email = validated_data['email'],
            firstname = validated_data['firstname'],
            lastname = validated_data['lastname'],
            mobile = validated_data['mobile']
        )

        user.set_password(validated_data['password'])
        user.save()

        return user


class UserSummarySerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = models.UserSummary
        fields = '__all__'
        depth = 1

这种方式的缺点是,创建新用户时,字段密码在 POST 请求中不再可用。

我怎样才能隐藏passwordUserSummary 的 GET 请求中的字段,但在 User 的 POST 请求中显示它?


这里的技巧是在“fields”元组中包含“password”字段,以便密码同时显示在“GET”和“POST”中,然后添加“extra_kwargs”以强制“password”字段仅出现在“POST”中形式。代码如下:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email',
              'is_active', 'is_staff', 'is_superuser', 'password',)

        # These fields are displayed but not editable and have to be a part of 'fields' tuple
        read_only_fields = ('is_active', 'is_staff', 'is_superuser',)

        # These fields are only editable (not displayed) and have to be a part of 'fields' tuple
        extra_kwargs = {'password': {'write_only': True, 'min_length': 4}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Django REST Framework 中隐藏 GET 中的密码字段,但不隐藏 POST 中的密码字段,其中序列化程序中的深度 = 1 的相关文章

随机推荐