should i use is_valid() function for validating my user data in put() function in drf? because when i use it ,is_valid.errors says that model with this username and email is already exists!i can't understand the errors meaning,because i think should be something saved before i want to update
serializers.py
class UserCreateSerializers(ModelSerializer):
class Meta:
model = User
fields = ('name','email','family',"username","password","profile_pic")
def update(self, instance, validated_data):
print("from update try")
#more dry
for i in validated_data.keys():
if hasattr(instance,str(i)) and str(i) !="password":
setattr(instance,str(i),validated_data.get(str(i)))
elif hasattr(instance,str(i)) and str(i) =="password":
instance.set_password(validated_data.get('password'))
setattr(instance,"username",validated_data.get('new_username'))
instance.save()
views.py
def put(self,request):
username = request.data['username']
user = User.objects.get(username = username)
serialized = UserCreateSerializers(data = request.data)
if serialized.is_valid():
serialized.update(user,serialized.validated_data)
return Response(data ={"status":"api_user_update_ok"} , status = status.HTTP_201_CREATED)
else:
print(serialized.errors)
return Response(data = {"status":"api_user_update_failed","error":serialized.errors.get('email')[0]},status = status.HTTP_400_BAD_REQUEST)
client data with put method :
name:user
family:useri
username:user2
password:1234
new_username:user22
email:[email protected]
error is :
{'email': [ErrorDetail(string='user with this email already exists.', code='unique')], 'username': [ErrorDetail(string='user with this username already exists.', code='unique')]} Bad Request: /api/v0/registration/signup
and the server response is :
{
"status": "api_user_update_failed",
"error": "user with this email already exists."
}
thanks for your help.