简体   繁体   English

如何使用Django REST Framework(DRF)3创建django用户

[英]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.

相关问题 通过在 DRF 中扩展用户模型进行身份验证(Django Rest Framework) - Authentication by extending User model in DRF (Django Rest Framework) 如何在 django rest_framework 的 1 个视图中同时创建 2 个不同的对象? DRF - How to Create 2 different objects at the same time in 1 view in django rest_framework? DRF 如何在 django rest 框架 (DRF) 中创建有助于 OneToOne 关系的两个模型的新实例? - How to create new instances of both models contributing in OneToOne relationship in django rest framework (DRF)? Django Rest Framework 创建用户和用户配置文件 - Django Rest Framework create user and user profile 如何覆盖 django rest 框架( DRF )中的响应类? - how overwrite Response class in django rest framework ( DRF )? Django Rest 框架(DRF)如何获取GenericRelation字段的值? - Django Rest Framework (DRF) how to get value of GenericRelation field? 制作Django Rest框架(DRF)工作流的方法 - Approach for making a Django Rest Framework (DRF) Workflow 如何在没有密码的情况下在 Django rest 框架中创建自定义用户? - How to create custom user in Django rest framework without a password? 如何在 Django Rest Framework 中为用户登录创建 Json Web 令牌? - How to create Json Web Token to User login in Django Rest Framework? django rest 框架使用密码创建用户 - django rest framework create user with password
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM