Quantcast
Viewing all articles
Browse latest Browse all 5

Answer by neferpitou for Why isn't my Django User Model's Password Hashed?

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

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>