How to register users in Django REST framework?

前端 未结 9 1464
说谎
说谎 2020-11-28 17:34

I\'m coding a REST API with Django REST framework. The API will be the backend of a social mobile app. After following the tutorial, I can serialise all my models and I am a

9条回答
  •  失恋的感觉
    2020-11-28 18:06

    The simplest solution, working in DRF 3.x:

    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ('id', 'username', 'password', 'email', 'first_name', 'last_name')
            write_only_fields = ('password',)
            read_only_fields = ('id',)
    
        def create(self, validated_data):
            user = User.objects.create(
                username=validated_data['username'],
                email=validated_data['email'],
                first_name=validated_data['first_name'],
                last_name=validated_data['last_name']
            )
    
            user.set_password(validated_data['password'])
            user.save()
    
            return user
    

    No need for other changes, just make sure that unauthenticated users have the permission to create a new user object.

    write_only_fields will make sure passwords (actually: their hash we store) are not displayed, while the overwritten create method ensures that the password is not stored in clear text, but as a hash.

提交回复
热议问题