From 6eb0e4e6b31e0f85dcd1231be49be671087bc7b8 Mon Sep 17 00:00:00 2001 From: stumpylog <797416+stumpylog@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:02:40 -0800 Subject: [PATCH] Fix: reject a custom field on zones with a built-in target Title, ASN and created zones stored a custom field that was then ignored. --- src/documents/serialisers.py | 10 ++++ src/documents/tests/test_api_ocr_templates.py | 60 +++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index ede858700e..4e914e1da0 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -3795,6 +3795,16 @@ class OcrTemplateZoneSerializer(serializers.ModelSerializer): raise serializers.ValidationError( {name: field.error_messages["required"]}, ) + # A custom field target may be left unassigned, as the editor creates new + # zones; built-in targets never use a custom field. + if ( + data.get("target", OcrTemplateZone.TargetType.CUSTOM_FIELD) + != OcrTemplateZone.TargetType.CUSTOM_FIELD + and data.get("custom_field") is not None + ): + raise serializers.ValidationError( + {"custom_field": "Only zones targeting a custom field can set one."}, + ) return data diff --git a/src/documents/tests/test_api_ocr_templates.py b/src/documents/tests/test_api_ocr_templates.py index 6a4d4af4fb..89d9046e7d 100644 --- a/src/documents/tests/test_api_ocr_templates.py +++ b/src/documents/tests/test_api_ocr_templates.py @@ -1056,6 +1056,66 @@ class TestOcrTemplateValidation: ) assert response.status_code == status.HTTP_400_BAD_REQUEST + @pytest.mark.parametrize( + ("target", "use_field", "expected"), + [ + pytest.param( + "custom_field", + True, + status.HTTP_201_CREATED, + id="custom-field-with-field", + ), + pytest.param( + "custom_field", + False, + status.HTTP_201_CREATED, + id="custom-field-unassigned", + ), + pytest.param("title", False, status.HTTP_201_CREATED, id="title"), + pytest.param( + "title", + True, + status.HTTP_400_BAD_REQUEST, + id="title-with-field", + ), + pytest.param( + "created", + True, + status.HTTP_400_BAD_REQUEST, + id="created-with-field", + ), + ], + ) + def test_only_custom_field_targets_set_a_custom_field( + self, + admin_client: APIClient, + text_field: CustomField, + target: str, + use_field: bool, # noqa: FBT001 + expected: int, + ) -> None: + """ + GIVEN: + - A zone with a custom field or built-in target, with or without a + custom field + WHEN: + - Create is attempted + THEN: + - A custom field target is accepted with or without a field + - A built-in target is rejected when it sets a custom field + """ + zone = zone_payload(text_field.pk if use_field else None, target=target) + + response = admin_client.post( + ENDPOINT, + template_payload(zones=[zone]), + format="json", + ) + + assert response.status_code == expected + if expected == status.HTTP_400_BAD_REQUEST: + assert "custom_field" in response.json()["zones"]["0"] + @pytest.mark.parametrize( ("pattern", "expected"), [