且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django REST框架中的其他序列化程序字段3

更新时间:2022-10-24 10:33:33

You are looking for a write-only field, as I'm assuming you won't want to display the password confirmation in the API. Django REST Framework introduced the write_only parameter in the 2.3.x timeline to complement the read_only parameter, so the only time validation is run is when an update is being made. The write_only_fields meta property was added around the same time, but it's important to understand how both of these work together.

The write_only_fields meta property will automatically add the write_only property to a field when it is automatically created, like for a password field on a User model. It will not do this for any fields which are not on the model, or fields that have been explicitly specified on the serializer. In your case, you are explicitly specifying the confirm_password field on your serializer, which is why it is not working.

Got KeyError when attempting to get a value for field confirm_password on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the OrderedDict instance

This is raised during the re-serialization of the created user, when it is trying to serialize your confirm_password field. Because it cannot find the field on the User model, it triggers this error which tries to explain the problem. Unfortunately because this is on a new user, it tells you to confusingly look at the OrderedDict instance instead of the User instance.

class UserSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(allow_blank=False, write_only=True)

If you explicitly specify write_only on the serializer field, and remove the field from your write_only_fields, then you should see the behaviour your are expecting.

You can find documentation about this on this link