2

I have the error:

You cannot call .save() after accessing serializer.data.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead.

Even if I'M NOT accesing serialized.data but serialized.validate_data.

Here is my code:

views.py

class Login(APIView):
    """
    Verify the login given is correct. #FIXME
    """
    def post(self, request, format=None):
        """Process the user given

        """

        serializer = LoginSerializer(data=request.data)

        if not serializer.is_valid():
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
            )

        if serializer.verify_user(serializer.validated_data):
            serializer.save()
            return Response(
                serializer.data,
                status=status.HTTP_201_CREATED
            )

verify_user is a custom function I did. If I don't use validated_data in that function, save() is executing. If not It gives that message. Inside I don't modify validated_data:

serializers.py

class LoginSerializer(serializers.Serializer):
    """Interface fields for login api
    """

    username = serializers.CharField(max_length=50)
    password = serializers.CharField(max_length=255)
    origin = serializers.CharField(max_length=255, required=False)

    def verify_user(self, validated_data):
        """
        Try to authenticate a user with given credentials
        :return: True on success
        """

        password_valid = validated_data['password']
        username_valid = validated_data['username']
        # TODO: Put in utilities
        _password_crp = self.cryp_password(password_valid)

        # 1 verify new table
        user = User.objects.filter(
            username=username_valid,
            password=_password_crp
        )
        if user is None or user.count() == 0:
            return False
        return True

1 Answer 1

7

The problem is in debug mode, because in debug mode you acccess to the object even if you don't access explicity but the debugger does.

1
  • I was tearing my hair out about this. It was the debugger. Why is DRF so fussy about accessing the serializer data anyway? It's so stupid!
    – Csaba Toth
    May 18, 2018 at 17:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.