0
votes

what i wanted was to send a post request with body containing email , username , password and password 2.

the serializer class has a save method which has been overriden so that it checks password1 is equal to password2 or not . if equal i wanted a user object to be created with email username and a password . and wanted it to be saved . im using User model of django.

error: TypeError: Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class tha t is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the RegistrationSerializer.create() method to handle this correctly.

Serializer Class:

class RegistrationSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = User
        fields = ['email', 'username', 'password','password2']
        extra_kwargs = {'password': {'write_only': True}}

        # override one of its method to check if passwords match

        def save(self):
            user = User()
            #cant create user py passing into constructor
            user.email=self.validated_data['email']
            user.username=self.validated_data['username']
            password=self.validated_data['password']
            password2=self.validated_data['password2']
            if password!=password2:
                raise serializers.ValidationError({'password':'password must match'})
            user.set_password(password)
            user.save()
            return user

the view called:


@api_view(['POST', ])
def registration_view(request):
    serializer=RegistrationSerializer(data=request.data)

    data={}
    if serializer.is_valid():
        user=serializer.save()
        data['response']="successfully created"
        data['email']=user.email
        data['username']=user.username
    else:
        data=serializer.errors
    return Response(data)
1
Is the indentation on the save method for real of just a formatting issue while posting? If it is not, I would suggest correcting it.Rajesh Yogeshwar
@RajeshYogeshwar Yogeshwar oh yah thx i forgot i put save functiuon in meta class.TonyMontana

1 Answers

0
votes

As save method is not good place for validation, You should use validate function when you want control some fields are correct.

class RegistrationSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = User
        fields = ['email', 'username', 'password','password2']
        extra_kwargs = {'password': {'write_only': True}}


    def validate(self, attrs):
        if attrs.get('password') != attrs.get('password2'):
            raise serializers.ValidationError({'password':'password must match'})
        return attrs

    def create(self, validated_data):
        password2 = validated_data.pop('password2')
        return super().create(validated_data)

If you want looks save function http://www.cdrf.co/3.9/rest_framework.serializers/ModelSerializer.html#save