diff --git a/netbox/users/models.py b/netbox/users/models.py index 02356696f..ea5762232 100644 --- a/netbox/users/models.py +++ b/netbox/users/models.py @@ -108,7 +108,7 @@ class UserConfig(models.Model): userconfig.clear('foo.bar.baz') - A KeyError is raised in the event any key along the path does not exist. + Invalid keys will be ignored silently. :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar']. :param commit: If true, the UserConfig instance will be saved once the new value has been applied. @@ -117,11 +117,13 @@ class UserConfig(models.Model): keys = path.split('.') for key in keys[:-1]: - if key in d and type(d[key]) is dict: + if key not in d: + break + if type(d[key]) is dict: d = d[key] key = keys[-1] - del(d[key]) + d.pop(key, None) # Avoid a KeyError on invalid keys if commit: self.save() diff --git a/netbox/users/tests/__init__.py b/netbox/users/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/netbox/users/tests/test_models.py b/netbox/users/tests/test_models.py index 0157d8fdd..8047796c4 100644 --- a/netbox/users/tests/test_models.py +++ b/netbox/users/tests/test_models.py @@ -104,6 +104,5 @@ class UserConfigTest(TestCase): self.assertTrue('foo' not in userconfig.data['b']) self.assertEqual(userconfig.data['b']['bar'], 102) - # Clear an invalid value - with self.assertRaises(KeyError): - userconfig.clear('invalid') + # Clear a non-existing value; should fail silently + userconfig.clear('invalid')