Skip to content

Commit 53000ed

Browse files
committed
Refuse to change multi to single attribute if there are values
Prevent users from accidentally changing multi attributes to single ones without changing all the attribute values before to contain only one.
1 parent ba5c5b6 commit 53000ed

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

serveradmin/serverdb/forms.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from django import forms
22
from django.core.exceptions import ValidationError
3+
from django.db.models.aggregates import Count
34

4-
from serveradmin.serverdb.models import ServertypeAttribute, Attribute
5+
from serveradmin.serverdb.models import ServertypeAttribute, Attribute, ServerStringAttribute
56

67

78
class ServertypeAdminForm(forms.ModelForm):
@@ -41,12 +42,20 @@ class Meta:
4142
fields = '__all__'
4243

4344
def clean(self):
44-
attr_type = self.cleaned_data.get('type') or self.instance.type # New or existing attribute ?
45+
attr_type = self.cleaned_data.get('type') or self.instance.type # New or existing attribute ?
4546

4647
if attr_type != 'relation' and self.cleaned_data.get('target_servertype') is not None:
4748
raise ValidationError('Attribute type must be relation when target servertype is selected!')
4849

4950
if attr_type == 'inet' and self.cleaned_data.get('multi') is True:
5051
raise ValidationError('Multi attributes of type inet are not supported!')
5152

52-
super().clean()
53+
if self.cleaned_data.get('multi') is False:
54+
any_attrs_have_multiple_values = ServerStringAttribute.get_model(self.instance.type).objects.filter(
55+
attribute_id=self.instance.attribute_id).values('server_id').annotate(
56+
occurences=Count('server_id')).filter(occurences__gt=1).exists()
57+
if any_attrs_have_multiple_values:
58+
raise ValidationError(
59+
'Refusing to make attribute type single because one ore more objects still have multiple values!')
60+
61+
super().clean()

0 commit comments

Comments
 (0)