Why isn't my Django User Model's Password Hashed?

后端 未结 4 598
野趣味
野趣味 2020-12-05 15:06

I am using the Django REST Framework (DRF) to create an endpoint with which I can register new users. However, when I hit the creation endpoint with a POST, the new user is

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 15:58

    Here is an alternative to accepted answer.

    class CreateUserSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = User
            fields = ('email', 'username', 'password')
            extra_kwargs = {'password': {'write_only': True}}
    
        def create(self, validated_data):
            user = User.objects.create_user(
                email=validated_data['email'],
                username=validated_data['username'],
                password=validated_data['password'],
            )
            user.save()
            return user
    

    create_user function is defined in UserManager and it uses set_password(), we don't need to use it explicitly. I have found many answers and articles which suggest to use set_password but after trying many things I figured the above and it works with CustomUserManager too. Suppose phone number and password is required to register a user. So our CustomUserManager will look something like this and CreateUserSerializer will handle this too with no changes.

    
    class CustomUserManager(BaseUserManager):
    
        def create_user(self, phone_number, password):
            if not phone_number:
                raise ValueError('Phone Number must be set')
    
            user = self.model(phone_number=phone_number)
            user.set_password(password)
            user.save(using=self._db)
            return user
    

提交回复
热议问题