简体   繁体   English

如何通过基于django_rest_framework的API处理用户注册

[英]How to handle user registration over django_rest_framework based API

How do I handle user registration over and API using django_rest_framework? 如何使用django_rest_framework处理用户注册和API? Specifically, how would I set up a password field in the UserSerializer 具体来说,我将如何在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)

You can just use a CharField for password. 您可以仅使用CharField作为密码。 And you even dont need a restore_object at all. 而且,您甚至根本不需要restore_object。 You can just do it like this, define fields like you do and then : 您可以这样做,定义字段,然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM