【问题标题】:Python Django Restframework Password Validation does not workPython Django Restframework密码验证不起作用
【发布时间】:2021-04-18 14:46:10
【问题描述】:

一开始我也看到this的帖子,但这对我不起作用。

我有一个 Django Rest 框架项目。如果我直接通过 django 创建用户,我会收到如下错误:

但如果我有一个正常的 HTTP POST 请求,我会得到一个正常的 200 响应:

{"email": "test@test.com", "response": "successfully registered new user.", "token": "3618d0c362dd66bbb093e1234b72901f9d74a905", "username": "haha"}

有什么问题?我还尝试为密码构建自定义验证,但这并不是我真正想要的,因为它是一个很棒的 Django 功能。

api/serializers.py

class RegistrationSerializer(serializers.ModelSerializer):


    class Meta:
        model = Account
        fields = ['email', 'username', 'password', 'password2',]

    def save(self):
        account = Account(
                email = self.validated_data['email'],
                username = self.validated_data['username'],
            )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        account.set_password(password)
        account.save()


api/views.py

@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = 'successfully registered new user.'
            data['email'] = account.email
            data['username'] = account.username
            token = Token.objects.get(user = account).key
            data['token'] = token
        else:
            data = serializer.errors
            print(data)
        return Response(data)

也许你有同样的问题?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    问题是,您没有密码验证。所以很简单:

    api/serializers.py

    from django.contrib.auth.password_validation import validate_password
    ...
    class RegistrationSerializer(serializers.ModelSerializer):
    
    
        class Meta:
            model = Account
            fields = ['email', 'username', 'password', 'password2',]
    
        def save(self):
            account = Account(
                    email = self.validated_data['email'],
                    username = self.validated_data['username'],
                )
            password = self.validated_data['password']
            password2 = self.validated_data['password2']
            if password != password2:
                raise serializers.ValidationError({'password': 'Passwords must match.'})
    ->      validate_password(password)
            account.set_password(password)
            account.save()
    
    

    【讨论】:

    • 非常感谢:)
    猜你喜欢
    • 2018-06-10
    • 1970-01-01
    • 2021-05-16
    • 2017-10-03
    • 2018-07-18
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多