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

问题描述 投票:0回答:4

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

class User (AbstractUser):
        bio = models.TextField(max_length=500, blank=True)
        birth_date = models.DateField(null=True, blank=True)
        image=models.FileField(null=True , blank=True)

我的序列化器是:

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

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

python django django-rest-framework django-serializer
4个回答
5
投票

哈希密码,请致电:

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)

2
投票

DRF中没有密码专用字段。在我目前的项目中,我们使用CharField在serializer类中定义密码字段为write_only=True


2
投票

更改serializers.py如下

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

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

1
投票

@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()
© www.soinside.com 2019 - 2024. All rights reserved.