[英]How to create a django User with Django REST Framework (DRF) 3
I'm trying to use Django Rest Framework 3.1.1 to create a user in a POST. 我正在尝试使用Django Rest Framework 3.1.1在POST中创建用户。 I need to use the built-in method to create the encrypted password so I've tried to override the save method on the ModelSerializer but I clearly don't know Django / DRF well enough to do this. 我需要使用内置方法来创建加密密码,因此我尝试覆盖ModelSerializer上的save方法,但是我显然不十分了解Django / DRF。 Is there a straightforward way to accomplish this? 有没有简单的方法可以做到这一点?
When I try the code below, I get an error: 当我尝试下面的代码时,出现错误:
unbound method set_password() must be called with User instance as first argument (got unicode instance
instead) 代替)
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
def save(self):
email = self.validated_data['email']
username = self.validated_data['username']
password = User.set_password(self.validated_data['password'])
Try doing something like this instead: 尝试做这样的事情:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'username', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email']
username=validated_data['username'],
)
user.set_password(validated_data['password'])
user.save()
return user
Since you are using a ModelSerializer
, you can override the perform_create()
function in your view and then set the password for the user. 由于您正在使用ModelSerializer
,因此可以在视图中覆盖perform_create()
函数,然后为用户设置密码。
DRF has provided this hook to add some custom actions which should occur before or after saving an object. DRF提供了此挂钩,以添加一些自定义操作,这些操作应在保存对象之前或之后进行。
As per DRF3 documentation: 根据DRF3文档:
These override points are particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. 这些替代点对于添加在保存对象之前或之后发生的行为(例如通过电子邮件发送确认或记录更新)特别有用。
from django.contrib.auth.hashers import make_password
class MyView(..):
...
def perform_create(self, serializer):
hashed_password = make_password(serializer.validated_data['password']) # get the hashed password
serializer.validated_data['password'] = hashed_password
user = super(MyView, self).perform_create(serializer) # create a user
Since, Django stores the password in hashed format and not as raw passwords, we use Django's make_password()
to get the raw password in hashed format. 由于Django以散列格式而不是原始密码存储密码,因此我们使用Django的make_password()
获取散列格式的原始密码。 We then set the password
in validated_data
of the serializer to this hashed password. 然后,我们将序列化程序的validated_data
中的password
设置为此哈希密码。 This hashed password is then used by the serializer when creating the user by calling the super()
. 然后,在通过调用super()
创建用户时,序列化程序将使用此哈希密码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.