简体   繁体   English

Django REST Framework 用户注册验证混淆

[英]Django REST Framework user registration Validation confusion

I am trying to register a user with Django REST API with two different methods我正在尝试使用two different methods向 Django REST API 注册用户

With method 1 everything works fine but it gives使用method 1一切正常,但它给出

This problem :这个问题 :

https://stackoverflow.com/questions/43952178/django-rest-framework-user-registration-confusion https://stackoverflow.com/questions/43952178/django-rest-framework-user-registration-confusion

And with method 2 it gives the following error but is creating users in backend使用method 2它会出现以下错误,但正在后端创建用户

AttributeError at /api/users/register/ /api/users/register/ 处的属性错误

Got AttributeError when attempting to get a value for field password2 on serializer UserCreateSerializer .尝试获取序列化程序UserCreateSerializer上的字段password2的值时出现UserCreateSerializer The serializer field might be named incorrectly and not match any attribute or key on the User instance.序列化器字段可能命名不正确,并且与User实例上的任何属性或键都不匹配。 Original exception text was: 'User' object has no attribute 'password2'.原始异常文本是:“用户”对象没有属性“password2”。

Code:代码:

from django.contrib.auth import get_user_model
from rest_framework.exceptions import ValidationError

from rest_framework.serializers import (ModelSerializer,CharField)

User = get_user_model()


class UserCreateSerializer(ModelSerializer):
    password2 = CharField(label='Confirm Password')
    class Meta:
        model = User
        fields = [
            'username',
            'password',
            'password2',
            'email',
        ]
        extra_kwargs = {
            'password' : {'write_only': True},
            'password2': {'write_only': True},
        }

    def validate_password(self, value):
        data = self.get_initial()
        password = data.get('password2')
        password2 = value
        if password != password2:
            raise ValidationError('Passwords must match')
        return value

    def validate_password2(self, value):
        data = self.get_initial()
        password = data.get('password')
        password2 = value
        if password != password2:
            raise ValidationError('Passwords must match')
        return value

method 1:方法一:

def create(self, validated_data):
    username = validated_data['username']
    email = validated_data['email']
    password = validated_data['password']
    user_obj = User(
        username=username,
        email=email
    )
    user_obj.set_password(password)
    user_obj.save()
    return validated_data

method 2:方法二:

 def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            username=validated_data['username'],
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

Note: Using Python3 , Django 10.7 & Django REST framework 3注意:使用 Python3、Django 10.7 和 Django REST framework 3

The problem in your method is that you are passing the password2, which is not an attribute of the User model.您的方法中的问题是您正在传递 password2,它不是 User 模型的属性。

From reading your code, I think you could try something like this,通过阅读你的代码,我认为你可以尝试这样的事情,

Instead of repeatedly validating each password field you could do an object wide validation for that.您可以为此进行对象范围的验证,而不是反复验证每个密码字段。

def validate(self, data):
    password = data.get('password')
    confirm_password = data.pop('password2')
    if password != confirm_password:
        raise ValidationError('.............')
    return data

The create method you have written would suffice, I hope.. Try this and let me know if anything comes up..你写的 create 方法就足够了,我希望..试试这个,如果出现任何问题,请告诉我..

EDIT编辑

Edit your create method,编辑您的创建方法,

def create (self, validated_data):
    email = validated_data.get('email')
    username = validated_data.get('username')
    password = validated_data.get('password')
    try:
        user = User.objects.create(username=username, email=email)
        user.set_password(password)
        user.save()
        return user
    except Exception as e:
        return e

The KeyError maybe triggered, if any of the email, password, username are not available.如果电子邮件、密码、用户名中的任何一个不可用,则可能会触发 KeyError。

please try this: add write_only=True in the password2请试试这个:在password2添加write_only=True

class UserCreateSerializer(ModelSerializer):
    password2 = CharField(label='Confirm Password', write_only=True)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM