Skip to content

Commit 03d138b

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 03d138b

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

serveradmin/serverdb/forms.py

Lines changed: 13 additions & 4 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):
@@ -24,8 +25,8 @@ def clean(self):
2425
# It makes no sense to add inet or supernet attributes to hosts of
2526
# ip_addr_type null because they would have to be empty anyways.
2627
inet_attribute = (
27-
self.cleaned_data['attribute'].type in ('inet', 'supernet') and
28-
self.instance.servertype.ip_addr_type == 'null'
28+
self.cleaned_data['attribute'].type in ('inet', 'supernet') and
29+
self.instance.servertype.ip_addr_type == 'null'
2930
)
3031
if inet_attribute:
3132
raise ValidationError(
@@ -49,4 +50,12 @@ def clean(self):
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)