2
votes

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.

1

1 Answers

2
votes

Short answer: yes you should use is_valid() before try to save received data into DB. You see this error because DRF add uniqueness validator to unique fields by default. This behavior described in the doc.

To tell django that you are updating object and don't need uniqueness validator you have to provide instance to serializer:

serialized = UserCreateSerializers(user, data=request.data)