繁体   English   中英

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

[英]Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer

我有 2 个模型:User 和 UserSummary。 UserSummary 有一个用户的外键。 我刚刚注意到,如果我在UserSummarySerializer设置depth= 1 ,则密码字段将包含在输出中。 它被散列,但最好还是排除这个字段。

为了隐藏密码字段,我刚刚在序列化程序中明确设置了用户字段,就像这样:

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 请求中不再提供字段密码。

如何在 UserSummary 的 GET 请求中隐藏password字段,但在 User 的 POST 请求中显示它?

这里的技巧是在“字段”元组中包含“密码”字段,以便密码显示在“GET”和“POST”中,然后添加“extra_kwargs”以强制“密码”字段仅出现在“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}}

当您将所有函数序列化器都放在一个时,这很复杂,我将在这种情况下创建一个UserCreateSerializer

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

    class Meta:
        model = models.User
        extra_kwargs = {'password': {'write_only': True}}
        fields = ['username', 'password', 'email', 'firstname', 'lastname', 'mobile'] # there what you want to initial.

    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

然后您可以在UserCreateSerializer中使用UserCreateAPIView

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User

    def to_representation(self, obj):
        rep = super(UserSerializer, self).to_representation(obj)
        rep.pop('password', None)
        return rep

要使您的密码不显示密码,您需要更改样式如下 -

password = serializers.CharField(
    style={'input_type': 'password'}
    )

就是这样。 我希望它有帮助。

在 Serializers.py 文件中进行更改

password = serializers.CharField( 
           style={'input_type': 'password'},
           min_length=6, 
           max_length=68, 
           write_only=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM