我有自定义用户模型。我已经为用户注册创建了一个api。以下是我的序列化器。
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[
UniqueValidator(queryset=get_user_model().objects.all())
]
)
password = serializers.CharField(min_length=8)
class Meta:
model = get_user_model()
fields = ('email', 'password')
extra_kwargs = {'password': {'write_only': True}, }
def create(self, validated_data):
email = validated_data.pop('email')
password = validated_data.pop('password')
user = get_user_model().objects.create_user(email, password, **validated_data)
return user
以下是我的观点:
class Registration(generics.CreateAPIView):
serializer_class = UserSerializer
queryset = get_user_model().objects.all()
有两个输入email
和password
。 password
字段以write_only字段的形式给出。但是在创建用户之后,api会返回哈希密码。如何防止返回密码?
答案 0 :(得分:4)
如果使用extra_kwargs
尝试这样做,则无需在序列化程序中明确声明该字段:
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[
UniqueValidator(queryset=get_user_model().objects.all())
]
)
class Meta:
model = get_user_model()
fields = ('email', 'password')
extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}