在 Django REST Framework 中隐藏 GET 中的密码字段但不隐藏 POST,其中序列化程序中的深度 = 1
Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer
我有 2 个模型:用户和用户摘要。 UserSummary 有一个指向 User 的外键。我刚刚注意到,如果我在 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 请求中显示它?
当你把所有的函数序列化器放在一起时,这很复杂,我会在这种情况下创建一个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
然后您可以在 UserCreateAPIView
中使用 UserCreateSerializer
。
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
这里的技巧是在 "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}}
要使您的密码不显示密码,您需要更改样式如下-
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)
我有 2 个模型:用户和用户摘要。 UserSummary 有一个指向 User 的外键。我刚刚注意到,如果我在 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 请求中显示它?
当你把所有的函数序列化器放在一起时,这很复杂,我会在这种情况下创建一个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
然后您可以在 UserCreateAPIView
中使用 UserCreateSerializer
。
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
这里的技巧是在 "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}}
要使您的密码不显示密码,您需要更改样式如下-
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)