[Answered ]-Django REST Framework user registration Validation confusion

2👍

The problem in your method is that you are passing the password2, which is not an attribute of the User model.

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..

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.

0👍

please try this: add write_only=True in the password2

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

Leave a comment