python - 如何使用 django rest 框架注册/登录

标签 python django authentication django-rest-framework

我正在用 django rest 框架开始我的第一个项目。
我通过使用电子邮件更改登录名来创建自己的自定义用户。
我想先注册一个用户,但我已经卡住了。 当我尝试创建一个时,出现错误'confirm_password' is an invalid keyword argument for this function

这是我的序列化程序:

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)
    confirm_password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Account
        fields =('id', 'email', 'username', 'date_joined', 'last_login', 'first_name', 'last_name', 'password', 'confirm_password')
        read_only_fields = ('last_login', 'date_joined')

        def create(self, validated_data):
            return Account.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.first_name = validated_data.get('first_name', instance.first_name)
            instance.last_name = validated_data.get('last_name', instance.last_name)
            instance.save()

            password = validated_data.get('password', None)
            confirm_password = validated_data.get('confirm_password', None)

            if password and confirm_password and password == confirm_password:
                instance.set_password(password)
                instance.save()

            update_session_auth_hash(self.context.get('request'), instance)

            return instance

这是我的看法:

class AccountViewSet(viewsets.ModelViewSet):
    # lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)
        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

        return Response({
            'status': 'Bad request',
            'message': 'les données ne sont pas valides'
            }, status=status.HTTP_400_BAD_REQUEST)

这是我从 django-custom-user 扩展的自定义用户:

class Account(AbstractEmailUser):
    username = models.CharField(unique=True, max_length=50)
    first_name = models.CharField(blank=True, null=True, max_length=50)
    last_name = models.CharField(blank=True, null=True, max_length=50)

我知道我收到错误是因为我的模型中没有字段确认密码,但我如何在没有双重输入的情况下验证密码?

我找不到任何关于使用 django rest 框架注册/登录的文档或教程,所以如果你知道一些我真的很感兴趣!

最佳答案

多读一点,似乎 ModelSerializer 不支持可写的非模型字段,所以一种方法可能是使用普通的 Serializer 类,像这样:

class AccountSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)
    confirmed_password = serializers.CharField(write_only=True)
    # ... and your other fields ...

    def validate(self, data):
        if data['password'] != data['confirmed_password']:
            raise serializers.ValidationError("passwords not match")
        return data

    def create(self, validated_data):
        # ... your create stuff ...

    def update(self, instance, validated_data):
        # ... and your update stuff ...

然后您可以像在 View 集中使用表单一样使用序列化程序:

In [17]: data = {'confirmed_password': '1234',
 'email': 'hello@world.com',
 'password': '1234',
 'username': 'test'}

In [18]: serializer = AccountSerializer(data=data)

In [19]: serializer.is_valid()
Out[19]: True

In [20]: serializer.data
Out[21]: {'email': u'hello@world.com', 'username': u'test', 'password': u'1234'}

In [23]: data = {'confirmed_password': '123456789',
 'email': 'hello@world.com',
 'password': '1234',
 'username': 'test'}

In [24]: serializer = AccountSerializer(data=data)

In [25]: serializer.is_valid()
Out[26]: False

In [27]: serializer.errors
Out[27]: {u'non_field_errors': [u'passwords not match']}

这是 doc,您可以在其中阅读有关序列化器的更多信息,希望对您有所帮助。

关于python - 如何使用 django rest 框架注册/登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29830937/

相关文章:

python - 带有 splinter 和 phantomjs 的 Django 非常慢

wcf - 使用 netTcpBinding 为 WCF 服务启用基于证书的身份验证

c# - WPF : How can i show my login window(project imported) before my application window?

python - 将多个值存储到 mysql 数据库中的单个字段中以保留 Django 中的顺序

python - 监听正在使用的端口

python - 在SQLAlchemy中,如何输入一个列表并获取表中符合条件的项目?

angular - 使用 MSAL 保护 ASP.Net Core Web API 和 Angular 应用程序

python - 按值将名称列表分组为 N 个列表

python - __length_hint__ 什么时候会不准确?

django - 跨应用程序使用 django 模型?