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)