mirror of
https://github.com/netbox-community/netbox.git
synced 2026-01-09 13:22:18 -06:00
Merge pull request #21065 from netbox-community/21049-clean-stale-cf-data
Fixes #21049: Remove stale custom field data during object validation
This commit is contained in:
@@ -1506,18 +1506,17 @@ class CustomFieldModelTest(TestCase):
|
|||||||
|
|
||||||
def test_invalid_data(self):
|
def test_invalid_data(self):
|
||||||
"""
|
"""
|
||||||
Setting custom field data for a non-applicable (or non-existent) CustomField should raise a ValidationError.
|
Any invalid or stale custom field data should be removed from the instance.
|
||||||
"""
|
"""
|
||||||
site = Site(name='Test Site', slug='test-site')
|
site = Site(name='Test Site', slug='test-site')
|
||||||
|
|
||||||
# Set custom field data
|
# Set custom field data
|
||||||
site.custom_field_data['foo'] = 'abc'
|
site.custom_field_data['foo'] = 'abc'
|
||||||
site.custom_field_data['bar'] = 'def'
|
site.custom_field_data['bar'] = 'def'
|
||||||
with self.assertRaises(ValidationError):
|
|
||||||
site.clean()
|
site.clean()
|
||||||
|
|
||||||
del site.custom_field_data['bar']
|
self.assertIn('foo', site.custom_field_data)
|
||||||
site.clean()
|
self.assertNotIn('bar', site.custom_field_data)
|
||||||
|
|
||||||
def test_missing_required_field(self):
|
def test_missing_required_field(self):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -288,12 +288,13 @@ class CustomFieldsMixin(models.Model):
|
|||||||
cf.name: cf for cf in CustomField.objects.get_for_model(self)
|
cf.name: cf for cf in CustomField.objects.get_for_model(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Remove any stale custom field data
|
||||||
|
self.custom_field_data = {
|
||||||
|
k: v for k, v in self.custom_field_data.items() if k in custom_fields.keys()
|
||||||
|
}
|
||||||
|
|
||||||
# Validate all field values
|
# Validate all field values
|
||||||
for field_name, value in self.custom_field_data.items():
|
for field_name, value in self.custom_field_data.items():
|
||||||
if field_name not in custom_fields:
|
|
||||||
raise ValidationError(_("Unknown field name '{name}' in custom field data.").format(
|
|
||||||
name=field_name
|
|
||||||
))
|
|
||||||
try:
|
try:
|
||||||
custom_fields[field_name].validate(value)
|
custom_fields[field_name].validate(value)
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
|
|||||||
Reference in New Issue
Block a user