本文介绍了如何在序列化程序中提及密码字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义用户进行身份验证,并想为其创建一个序列化程序类,我的自定义用户的模型如下:

I have a custom user for authentication and want to create a serializer class for it my custom user's model is like this :

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' )

我怎么能说 password字段是密码,并且必须对它的内容进行哈希处理?

how could I mention that the password field is a password and its content must be hashed?

推荐答案

要散列密码,请致电:

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)

这篇关于如何在序列化程序中提及密码字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:33