From 0bca50588d3effda9157ba7af4324c43fda1afb8 Mon Sep 17 00:00:00 2001 From: stumpylog <797416+stumpylog@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:05:39 -0800 Subject: [PATCH] Fix: drop a deleted custom field's combine format from OCR templates The template kept the stale key, so saving it again failed validation. --- src/documents/signals/handlers.py | 14 +++- src/documents/tests/test_api_ocr_templates.py | 78 +++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) diff --git a/src/documents/signals/handlers.py b/src/documents/signals/handlers.py index cdc9943277..70619be8a9 100644 --- a/src/documents/signals/handlers.py +++ b/src/documents/signals/handlers.py @@ -45,6 +45,8 @@ from documents.models import CustomField from documents.models import CustomFieldInstance from documents.models import Document from documents.models import DocumentType +from documents.models import OcrTemplate +from documents.models import OcrTemplateZone from documents.models import PaperlessTask from documents.models import SavedView from documents.models import StoragePath @@ -717,7 +719,8 @@ def check_paths_and_prune_custom_fields( @receiver(models.signals.post_delete, sender=CustomField) def cleanup_custom_field_deletion(sender, instance: CustomField, **kwargs) -> None: """ - When a custom field is deleted, ensure no saved views reference it. + When a custom field is deleted, ensure no saved views reference it and no + OCR template keeps a combine format for it. """ field_identifier = SavedView.DisplayFields.CUSTOM_FIELD % instance.pk # remove field from display_fields of all saved views @@ -740,6 +743,15 @@ def cleanup_custom_field_deletion(sender, instance: CustomField, **kwargs) -> No f"Removing custom field {instance} from sort field of {views_with_sort_updated} views", ) + # zone_ocr imports this module, so it cannot be imported at module level + from documents.zone_ocr import field_key + + combine_key = field_key(OcrTemplateZone.TargetType.CUSTOM_FIELD, instance.pk) + for template in OcrTemplate.objects.only("pk", "combine_formats"): + if combine_key in template.combine_formats: + del template.combine_formats[combine_key] + template.save(update_fields=["combine_formats"]) + @receiver(models.signals.post_save, sender=Document) def update_llm_suggestions_cache(sender, instance, **kwargs): diff --git a/src/documents/tests/test_api_ocr_templates.py b/src/documents/tests/test_api_ocr_templates.py index 256bf0d2e0..0a681adba6 100644 --- a/src/documents/tests/test_api_ocr_templates.py +++ b/src/documents/tests/test_api_ocr_templates.py @@ -1709,6 +1709,84 @@ class TestOcrTemplateDelete: assert zone.custom_field is None assert OcrTemplate.objects.filter(pk=template.pk).exists() + @pytest.mark.parametrize( + ("formats", "expected"), + [ + pytest.param( + {"{deleted}": "{A}", "{other}": "{B}", "title": "{C}"}, + {"{other}": "{B}", "title": "{C}"}, + id="removes-only-the-deleted-key", + ), + pytest.param( + {"{other}": "{B}", "title": "{C}"}, + {"{other}": "{B}", "title": "{C}"}, + id="without-the-key-is-unchanged", + ), + ], + ) + def test_deleting_a_custom_field_drops_its_combine_format( + self, + formats: dict[str, str], + expected: dict[str, str], + ) -> None: + """ + GIVEN: + - A template with combine formats for a custom field, another + custom field and the title target, or without the first key + WHEN: + - The first custom field is deleted + THEN: + - Only that custom field's key is removed from combine_formats + """ + deleted = CustomFieldFactory() + other = CustomFieldFactory() + resolve = {"{deleted}": str(deleted.pk), "{other}": str(other.pk)} + template = OcrTemplateFactory( + combine_formats={resolve.get(key, key): v for key, v in formats.items()}, + ) + + deleted.delete() + + template.refresh_from_db() + assert template.combine_formats == { + resolve.get(key, key): v for key, v in expected.items() + } + + def test_template_can_be_saved_after_its_custom_field_is_deleted( + self, + admin_client: APIClient, + text_field: CustomField, + ) -> None: + """ + GIVEN: + - A template with a custom field zone and a combine format for it + WHEN: + - The custom field is deleted and the template is saved again + with its stored combine_formats + THEN: + - The save succeeds, as the stale key was removed + """ + template = OcrTemplateFactory( + match="Northwind", + combine_formats={str(text_field.pk): "{A}"}, + ) + OcrTemplateZoneFactory( + template=template, + target=OcrTemplateZone.TargetType.CUSTOM_FIELD, + custom_field=text_field, + ) + text_field.delete() + template.refresh_from_db() + + response = admin_client.patch( + detail_url(template.pk), + {"combine_formats": template.combine_formats}, + format="json", + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["combine_formats"] == {} + def test_nonexistent_returns_404(self, admin_client: APIClient) -> None: """ GIVEN: