Adding custom_password field to UserSerializer without registering it to User model in Django REST API

I need a way to add the confirm_password field in the data my CreateUserView returns without creating it explicitly in my user model. I tried doing the following but it raised TypeError at /user/create/ User() got unexpected keyword arguments: 'confirm_password'. How can I solve this issue?

Thank you for all the response

Here is my code:

serializer.py

class CreateUserSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(
        max_length=100, write_only=True, required=False
    )

    class Meta:
        model = User
        fields = [
            "id",
            "email",
            "password",
            "confirm_password",
            "first_name",
            "last_name",
        ]
        extra_kwargs = {"password": {"write_only": True}, "id": {"read_only": True}}

    def create(self, validated_data):
        return User.objects.create_user(**trim_spaces_from_data(validated_data))

views.py

class CreateUserView(CreateAPIView):

    permission_classes = [permissions.AllowAny]
    serializer_class = CreateUserSerializer

    def create(self, request, *args, **kwargs):
        queryset = User.objects.filter(email=request.data["email"])

        if queryset.exists():
            raise CustomUserException("Provided email address is already in use")
        if not "confirm_password" in request.data.keys():
            raise CustomUserException("Confirm password field is required")
        if not request.data["password"] == request.data["confirm_password"]:
            raise CustomUserException("Passwords does not match")

        serializer = CreateUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(status=200, data=serializer.data)

Create a seperate serialiser for the confirm_password field (not a model serialiser). Then call the new made serialiser in your mode serialiser on the field confirm_password. In youre code the field confirm_password is not in youre user model so houre getting this error.

first_name = serializers.CharField()
last_name = serializers.CharField()
username = serializers.CharField()
email = serializers.EmailField()=
password = serializers.CharField()
confirm_password = serializers.CharField()

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields.pop('confirm_password')

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

just pop the confirm_password

Back to Top