0

如何使用django_rest_framework處理用戶註冊和API?具體來說,我將如何在UserSerializer中設置密碼字段如何通過基於django_rest_framework的API處理用戶註冊

class NewUserSerializer(serializer.Serializers): 
    first_name = serializers.CharField(required=True, max_length=30) 
    last_name = serializers.CharField(required=True, max_length=30) 
    username = serlializers.CharField(required=True, max_length=30) 
    email = serializers.EmailField(required=True) 
    password = ??? 

    def restore_object(self, attrs, instance=None): 
     if instance: 
      instance.username = attrs.get('username', instance.username) 
      instance.first_name = attrs.get('first_name', instance.first_name) 
      instance.last_name = attrs.get('last_name', instance.last_name) 
      instance.email = attrs.get('email', instance.email) 
# Would the instance.password field be necessary? 
      instance.password = attrs.get('password', instance.password) 
     else: 
      return User(**attrs) 

回答

1

您可以使用CharField作爲密碼。你甚至不需要一個restore_object。你可以這樣做,像你這樣定義字段:

serializer = NewUserSerializer(data=request.DATA) 
    if serializer.is_valid():   
     email = serializer.object["email"] 
     password = serializer.object["password"] 
     # do the stuff you want here 
+0

爲什麼我不想添加restore_object方法?如果用戶決定更改他們的電子郵件地址或密碼會怎麼樣? – user1876508 2013-05-08 21:42:22

+0

我只是意味着如果它註冊這個邏輯可以走出串行器。無論如何,如果您希望它返回實際的User對象實例,並且您的擔心是密碼,那麼您應該只使用CharField作爲密碼,而在restore_object中使用set_password方法,而不是直接分配。 – Aldarund 2013-05-08 23:46:39

相關問題