2016-11-10 96 views
0

我有用戶創建序列化程序,但它仍然是返回密碼和c_password字段。我如何刪除這個迴應。Django休息創建後刪除密碼

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

您的觀點是怎樣的? – e4c5

+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 
+0

對不起,未包含在用戶模型中的c_password。我剛剛添加獲取確認密碼。如果我返回user_obj。它給我一個錯誤c_password不是用戶字段。 c_password只是爲了驗證。我也在字段中聲明瞭c_password,如果不行的話會給出一個錯誤 –