Django Rest Framework: Disable field update after object is created

后端 未结 11 1394
独厮守ぢ
独厮守ぢ 2020-11-30 20:15

I\'m trying to make my User model RESTful via Django Rest Framework API calls, so that I can create users as well as update their profiles.

However, as I go through

11条回答
  •  借酒劲吻你
    2020-11-30 20:46

    Another solution (apart from creating a separate serializer) would be to pop the username from attrs in the restore_object method if the instance is set (which means it's a PATCH / PUT method):

    def restore_object(self, attrs, instance=None):
        if instance is not None:
            attrs.pop('username', None)
        user = super(UserSerializer, self).restore_object(attrs, instance)
        user.set_password(attrs['password'])
        return user
    

提交回复
热议问题