如何使用DRF的ModelSerializer创建一个django用户 [英] How to create a django User using DRF's ModelSerializer
问题描述
在django中,创建用户具有与通常的Model实例创建不同的唯一流。您需要调用 create_user()
,这是一个 BaseUserManager
的方法。
In django, creating a User has a different and unique flow from the usual Model instance creation. You need to call create_user()
which is a method of BaseUserManager
.
由于django REST框架的流程是要执行 restore_object()
然后 save_object()
,它不是可以在通用的创建API端点中简单地创建一个使用 ModelSerializer
的用户,而不会黑客攻击。
Since django REST framework's flow is to do restore_object()
and then save_object()
, it's not possible to simply create Users using a ModelSerializer
in a generic create API endpoint, without hacking you way through.
会是一个干净的方式来解决这个问题吗?或者至少使用django的内置管道来工作?
What would be a clean way to solve this? or at least get it working using django's built-in piping?
编辑:
重要的是要注意,特别不奏效的是,一旦您尝试使用 django.contrib.auth.authenticate
验证创建的用户实例,如果实例被简单创建,它将失败使用 User.objects.create()
而不是 .create_user()
。
Important to note that what's specifically not working is that once you try to authenticate the created user instance using django.contrib.auth.authenticate
it fails if the instance was simply created using User.objects.create()
and not .create_user()
.
推荐答案
最终我已经覆盖了序列化程序的 restore_object
方法,并确保正在发送的密码是使用 instance.set_password(password)
,如下所示:
Eventually I've overridden the serializer's restore_object
method and made sure that the password being sent is then processes using instance.set_password(password)
, like so:
def restore_object(self, attrs, instance=None):
if not instance:
instance = super(RegisterationSerializer, self).restore_object(attrs, instance)
instance.set_password(attrs.get('password'))
return instance
感谢大家r help!
Thanks everyone for help!
这篇关于如何使用DRF的ModelSerializer创建一个django用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!