Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions netbox/extras/tests/test_customfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1506,19 +1506,18 @@ def test_cf_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')

# Set custom field data
site.custom_field_data['foo'] = 'abc'
site.custom_field_data['bar'] = 'def'
with self.assertRaises(ValidationError):
site.clean()

del site.custom_field_data['bar']
site.clean()

self.assertIn('foo', site.custom_field_data)
self.assertNotIn('bar', site.custom_field_data)

def test_missing_required_field(self):
"""
Check that a ValidationError is raised if any required custom fields are not present.
Expand Down
9 changes: 5 additions & 4 deletions netbox/netbox/models/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,12 +288,13 @@ def clean(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
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:
custom_fields[field_name].validate(value)
except ValidationError as e:
Expand Down
Loading