Django 内置的User类提供了用户密码的存储、验证、修改等功能,默认使用pbkdf2_sha256方式来存储和管理用的密码。
以用户注册为例子
序列化器类设计
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
class RegisterModelSerializer(serializers.ModelSerializer):
password_confirm = serializers.CharField(label='确认密码', help_text='确认密码',
error_messages={"min_length": "允许输入5-20个字符",
"max_length": "允许输入5-20个字符", },
write_only=True)
token = serializers.CharField(label='token', help_text='token', read_only=True)
class Meta:
model = User
fields = ['id', 'username', 'password', 'password_confirm', 'token', 'email']
extra_kwargs = {
"username": {
"label": "用户名",
"help_text": "用户名",
"max_length": 20,
"min_length": 5,
"error_messages": {
"min_length": "允许输入5-20个字符",
"max_length": "允许输入5-20个字符",
},
"validators": [UniqueValidator(queryset=User.objects.all(), message='用户名已注册,请重新输入')]
},
"password": {
"label": "密码",
"help_text": "密码",
"max_length": 20,
"min_length": 5,
"error_messages": {
"min_length": "允许输入5-20个字符",
"max_length": "允许输入5-20个字符",
},
"write_only": True
},
"email": {
"label": "邮箱",
"help_text": "邮箱",
"max_length": 20,
"min_length": 5,
"required": True,
"write_only": True,
"validators": [UniqueValidator(queryset=User.objects.all(), message='邮箱已注册,请重新输入')]
}
}
# 校验密码与验证码密码
def validate(self, attrs):
password = attrs.get('password')
password_confirm = attrs.get('password_confirm')
if password_confirm != password:
raise serializers.ValidationError("密码和确认密码输入的不一致")
return attrs
def create_token(self, user):
payload = jwt_payload_handler(user)
return jwt_encode_handler(payload)
# 校验通过之后,创建模型对象
def create(self, validated_data):
user = User.objects.create_user(username=validated_data.get('username'),
password=validated_data.get('password'),
email=validated_data.get('email'),
)
token = self.create_token(user)
user.token = token
return user
首先服务端校验用户名.密码.确认密码.邮箱都成功后
接下来创建模型对象用create_user()
方法
用set_password(password)
进行密码加密
最后返回user对象,并且创建用户成功