From 1d6484bfe6bbdf763f6a9c583115c1c6b3914037 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Wed, 24 Jun 2020 17:37:59 +0200 Subject: Container - batch modification: check db constraint uniqueness on validation (refs #4951) --- archaeological_warehouse/forms.py | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'archaeological_warehouse/forms.py') diff --git a/archaeological_warehouse/forms.py b/archaeological_warehouse/forms.py index 9c39c61c5..6ea1ae4f6 100644 --- a/archaeological_warehouse/forms.py +++ b/archaeological_warehouse/forms.py @@ -593,6 +593,7 @@ class QAContainerFormMulti(QAForm): ] def __init__(self, *args, **kwargs): + self.items = kwargs["items"] super(QAContainerFormMulti, self).__init__(*args, **kwargs) locations = set([item.location_id for item in self.items]) if len(locations) == 1: @@ -609,3 +610,43 @@ class QAContainerFormMulti(QAForm): return models.Container.objects.get(pk=value).cached_label except models.Container.DoesNotExist: return "" + + def clean(self): + new_values = {} + if self.cleaned_data.get("qacontainer_type", None): + new_values["container_type_id"] = self.cleaned_data[ + "qacontainer_type"] + if self.cleaned_data.get("qalocation", None): + new_values["location_id"] = self.cleaned_data[ + "qalocation"] + if self.cleaned_data.get("qaparent", None): + new_values["parent_id"] = self.cleaned_data[ + "qaparent"] + new_tuples = [] + for item in self.items: + vals = { + "container_type_id": item.container_type_id, + "location_id": item.location_id, + "parent_id": item.parent_id, + "reference": item.reference.strip() + } + vals.update(new_values) + c_tuple = (vals["location_id"], vals["container_type_id"], + vals["parent_id"], vals["reference"]) + q = models.Container.objects.filter(**vals).exclude(id=item.id) + if c_tuple in new_tuples or q.count(): + parent = models.Container.objects.get(pk=vals["parent_id"]) + raise forms.ValidationError( + str( + _("Cannot do this changes because it would generate " + "many containers with location: {}, container type: " + "{}, parent: {} {} and reference: {}. " + "Merge theses containers first?")).format( + models.Warehouse.objects.get(pk=vals["location_id"]), + models.ContainerType.objects.get( + pk=vals["container_type_id"]), + parent.container_type, parent.reference, + vals["reference"] + ) + ) + return self.cleaned_data -- cgit v1.2.3