From bf82101e84b61a2c3eae44947c33de26926c756d Mon Sep 17 00:00:00 2001 From: Brian Tiemann Date: Tue, 17 Dec 2024 18:00:10 -0500 Subject: [PATCH 1/3] Validate that a scope has been selected if a scope_type is specified, on CachedScopeMixin models --- netbox/dcim/models/mixins.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/netbox/dcim/models/mixins.py b/netbox/dcim/models/mixins.py index ac4d7dab9ca..8bfa76572de 100644 --- a/netbox/dcim/models/mixins.py +++ b/netbox/dcim/models/mixins.py @@ -1,6 +1,8 @@ from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey +from django.core.exceptions import ValidationError from django.db import models +from django.utils.translation import gettext_lazy as _ from dcim.constants import LOCATION_SCOPE_TYPES __all__ = ( @@ -84,6 +86,16 @@ class CachedScopeMixin(models.Model): class Meta: abstract = True + def clean(self): + if self.scope_type: + scope_type = self.scope_type.model_class() + if not self.scope: + raise ValidationError({ + 'scope': _( + "Please select a {scope_type}." + ).format(scope_type=scope_type._meta.model_name) + }) + def save(self, *args, **kwargs): # Cache objects associated with the terminating object (for filtering) self.cache_related_objects() From 6a4c944e64093c05edd65e5dfa094c1dc3d403dc Mon Sep 17 00:00:00 2001 From: Brian Tiemann Date: Tue, 17 Dec 2024 21:12:48 -0500 Subject: [PATCH 2/3] Cleaner logic --- netbox/dcim/models/mixins.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/netbox/dcim/models/mixins.py b/netbox/dcim/models/mixins.py index 8bfa76572de..5d686d11092 100644 --- a/netbox/dcim/models/mixins.py +++ b/netbox/dcim/models/mixins.py @@ -87,14 +87,13 @@ class Meta: abstract = True def clean(self): - if self.scope_type: + if self.scope_type and not self.scope: scope_type = self.scope_type.model_class() - if not self.scope: - raise ValidationError({ - 'scope': _( - "Please select a {scope_type}." - ).format(scope_type=scope_type._meta.model_name) - }) + raise ValidationError({ + 'scope': _( + "Please select a {scope_type}." + ).format(scope_type=scope_type._meta.model_name) + }) def save(self, *args, **kwargs): # Cache objects associated with the terminating object (for filtering) From a710cec061178615a53b5ae4323b8b4463bb975b Mon Sep 17 00:00:00 2001 From: Brian Tiemann Date: Wed, 18 Dec 2024 14:04:09 -0500 Subject: [PATCH 3/3] Call super().clean() after validating scope_type/scope --- netbox/dcim/models/mixins.py | 1 + 1 file changed, 1 insertion(+) diff --git a/netbox/dcim/models/mixins.py b/netbox/dcim/models/mixins.py index 5d686d11092..a0fc15a2585 100644 --- a/netbox/dcim/models/mixins.py +++ b/netbox/dcim/models/mixins.py @@ -94,6 +94,7 @@ def clean(self): "Please select a {scope_type}." ).format(scope_type=scope_type._meta.model_name) }) + super().clean() def save(self, *args, **kwargs): # Cache objects associated with the terminating object (for filtering)