怎么在序列化器中提到密码字段?

时间:2018-03-09 08:27:47

标签: python django django-rest-framework django-serializer

我有一个自定义用户进行身份验证,并希望为其创建一个序列化程序类,我的自定义用户的模型是这样的:

class UserSerializer (serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username' ,'email' ,'password' ,'firstname' , 'last name' )

我的序列化器是:

setTimeout(() => {
  this.interval = setInterval(this.function, interval);
}, delay);

function(){.....}

我怎么能提到密码字段是密码而且其内容必须经过哈希处理?

4 个答案:

答案 0 :(得分:4)

要散列密码,请致电:

make_password(origin_password)

示例 serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password


class UserSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(
        write_only=True,
        required=True,
        help_text='Leave empty if no change needed',
        style={'input_type': 'password', 'placeholder': 'Password'}
    )

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'password')

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data.get('password'))
        return super(UserSerializer, self).create(validated_data)

答案 1 :(得分:1)

DRF中没有密码专用字段。在我当前的项目中,我们习惯将密码字段定义为CharField,并在序列化程序类中定义write_only=True

答案 2 :(得分:1)

如下所示更改serializers.py

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password', 'firstname', 'last name')

答案 3 :(得分:0)

@MahdiSorkhmiri的答案非常适合我。这是我的文件的样子,现在就写。

   class UserSerializer(serializers.ModelSerializer):
        email = serializers.EmailField(
        validators=[UniqueValidator(UserModel.objects.all())]
        )
        password = serializers.CharField(
        min_length=4,
        write_only=True,
        required=True,
        style={'input_type': 'password'}
        )
    def create(self, validated_data):
        fields = ['username', 'password', 'email']
        data = {f: validated_data.get(f) for f in fields}

        return UserModel.objects.create_user(**data)

    class Meta:
        model = UserModel
        fields = 'username email last_name first_name password'.split()