From 6a48e5397ecf71a20c041170f7cca5eedbc84fda Mon Sep 17 00:00:00 2001 From: Jonathan Weth <git@jonathanweth.de> Date: Fri, 22 Jul 2022 09:47:33 +0200 Subject: [PATCH] Add arg to regex field type to raise an exception if no match was found --- CHANGELOG.rst | 6 ++++++ aleksis/apps/csv_import/field_types.py | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2b8c367..a432f4a 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -9,6 +9,12 @@ and this project adheres to `Semantic Versioning`_. Unreleased ---------- +Added +~~~~~ + +* If activated, imports with regex field types will show error messages + when there is no match. + `2.3`_ - 2022-06-25 ------------------- diff --git a/aleksis/apps/csv_import/field_types.py b/aleksis/apps/csv_import/field_types.py index b7d00f3..07c3a89 100644 --- a/aleksis/apps/csv_import/field_types.py +++ b/aleksis/apps/csv_import/field_types.py @@ -144,16 +144,26 @@ class RegExFieldType(ProcessFieldType): data_type = str reg_ex: str = "" + fail_if_no_match: bool = False def get_reg_ex(self): return self.reg_ex or self.get_args().get("reg_ex", "") + def get_fail_if_no_match(self): + return self.fail_if_no_match or self.get_args().get("fail_if_no_match", False) + def process(self, instance: Model, value): match = re.fullmatch(self.get_reg_ex(), value) if match: for key, item in match.groupdict().items(): setattr(instance, key, item) instance.save() + elif self.get_fail_if_no_match(): + raise IndexError( + _("No match on {} for regular expression {} found.").format( + value, self.get_reg_ex() + ) + ) @field_type_registry.register -- GitLab