python 将django密码验证器与django rest framework validate_password集成

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 将django密码验证器与django rest framework validate_password集成相关的知识,希望对你有一定的参考价值。

import django.contrib.auth.password_validation as validators
from rest_framework import serializers

class RegisterUserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(style={'input_type': 'password'}, write_only=True)

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

    def validate_password(self, data):
        # validators.validate_password(password=data, user=User)
        # return data
        
        # here data has all the fields which have validated values
        # so we can create a User instance out of it
        user = User(**data)

        # get the password from the data
        password = data.get('password')

        errors = dict() 
        try:
            # validate the password and catch the exception
            validators.validate_password(password=password, user=user)

        # the exception raised here is different than serializers.ValidationError
        except exceptions.ValidationError as e:
            errors['password'] = list(e.messages)

        if errors:
            raise serializers.ValidationError(errors)

        return super(RegisterUserSerializer, self).validate(data)

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        user.is_active = False
        user.save()
        return user

以上是关于python 将django密码验证器与django rest framework validate_password集成的主要内容,如果未能解决你的问题,请参考以下文章

Django框架-- Djang与Ajax

创建djang+vue项目

Django

从Python / Django生成symfony 2.4密码

Django中使用geetest实现滑动验证

第十七章:Python の Web开发基础 MVC与Django