我有用户创建序列化程序,但它仍然返回密码和c_password字段。如何将其删除以进行回复。
class UserCreateSerializer(ModelSerializer):
phone = CharField(label='Phone number')
password = CharField(label='password')
c_password = CharField(label='confirm passowrd')
class Meta:
model = User
fields = [
'phone',
'username',
'password',
'c_password'
]
extra_kwargs = {"password": {"write_only": True},
"c_password": {"write_only": True}}
def create(self, validated_data):
phone = validated_data['phone']
username = validated_data['username']
password = validated_data['c_password']
user_obj = User(phone=phone, username=username)
user_obj.set_password(password)
user_obj.save()
return validated_data
class UserCreateAPIView(CreateAPIView):
permission_classes = [AllowAny]
serializer_class = UserCreateSerializer
queryset = User.objects.all()
我还尝试添加perform_create方法并返回自定义Response对象。但它返回带有密码的序列化程序对象。
答案 0 :(得分:1)
您将在create
方法中返回经过验证的数据。如果您只想要用户对象,只需返回该对象即可。例如:
class UserCreateSerializer(ModelSerializer):
phone = CharField(label='Phone number')
password = CharField(label='password')
c_password = CharField(label='confirm passowrd')
class Meta:
model = User
fields = [
'phone',
'username',
'password',
'c_password'
]
extra_kwargs = {"password": {"write_only": True},
"c_password": {"write_only": True}}
def create(self, validated_data):
phone = validated_data['phone']
username = validated_data['username']
password = validated_data['c_password']
user_obj = User(phone=phone, username=username)
user_obj.set_password(password)
user_obj.save()
return user_obj