2

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 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @neverwalkaloner this is solve my issue similair to the one above, just a side effect, if we have nested objects under the serializer is there more general approach to solve the issue instead of applying the same approach for each nested object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.