django rest framework create user with password

后端 未结 4 782
说谎
说谎 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:10

    In addition to @aliva's answer where you miss out on the functionalities in serializers.Modelserializer.create() (which could be quite nice to preserve, for example handling of many-to-many relations), there is a way to keep this.

    By using the user.set_password() method, the password can also be correctly set, like:

    class UserSerializer(serializers.ModelSerializer):
    
        def create(self, validated_data):
            user = super().create(validated_data)
            user.set_password(validated_data['password'])
            user.save()
            return user
    

    This has the benefit of keeping the super class' functionality, but the downside of an additional write to the database. Decide which trade-off is more important to you :-).

    Edit: Fix syntax error

    Edit2: jkatzer's comment makes a lot of sense. I don't have the environment set up at the moment to look at it, and i also don't recall if there was more changes I'd made to this solution that did not put in the post. But looking at it now I'm agreeing with this comment, should probably do something more in the lines of Alwx's answer....

提交回复
热议问题