1👍
✅
You can validate the two passwords fields with serializers validate(self, attrs) method
like this :
def validate(self, attrs):
if attrs['password1'] != attrs['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return attrs
in your case change your RegisterUserSerializer class like this :
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.validators import UniqueValidator
from django.contrib.auth.password_validation import validate_password
class RegisterUserSerializer(serializers.ModelSerializer):
password1 = serializers.CharField(write_only=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('email','user_name', 'password1', 'password2')
def validate(self, attrs):
if attrs['password1'] != attrs['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
user = User.objects.create(
username=validated_data['user_name'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
return user
Source:stackexchange.com