0

如何使用 django_rest_framework 处理用户注册和 API?具体来说,我将如何在 UserSerializer 中设置密码字段

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)
4

1 回答 1

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
于 2013-05-08T20:53:29.503 回答