0
votes

I am using django's inbuilt User model to create a registration api with Django REST framework (DRF). I want client to post a request like this

 {
    username:'user1',
    email:'[email protected],
    password:'password123',
    confirm_password:'password123'
}

The trouble is In the django's built in 'User' database have no field as confirm_password. I dont want to add additional columns to the database and need this false field only to validate the two passwords and not to included it in the database. I wrote this model serializer

class RegSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username', 'email', 'password', 'confirm_password')
        extra_kwargs = {'password': {'write_only': True},'confirm_password': {'write_only': True}}

and created user through

User.objects.create_user(request.data['username'], request.data['email'], request.data['password'])

But it shows this error

django.core.exceptions.ImproperlyConfigured: Field name confirm_password is not valid for model User.

How do we add an extra false field in the Django REST framework serilizer?

1

1 Answers

1
votes

You can define a new field to the serializer class as,

class RegSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password', 'confirm_password')
        extra_kwargs = {
            'password': {'write_only': True}
        }