django rest framework create user with password

后端 未结 4 803
说谎
说谎 2021-02-07 13:37

Using django-rest-framework 3 and django 1.8

I am trying to create a user using django-rest-framework ModelViewSerializer. problem is that the default objects.create m

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 14:05

    A complete example that support POST and PUT/PATCH without another SQL UPDATE statement.

    class MyUserSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.User
            fields = '__all__'
    
        def create(self, validated_data):
            if "password" in validated_data:
                from django.contrib.auth.hashers import make_password
                validated_data["password"] = make_password(validated_data["password"])
            return super().create(validated_data)
    
        def update(self, instance, validated_data):
            if "password" in validated_data:
                from django.contrib.auth.hashers import make_password
                validated_data["password"] = make_password(validated_data["password"])
            return super().update(instance, validated_data)
    

提交回复
热议问题