diff --git a/django_netjsonconfig/models/device.py b/django_netjsonconfig/models/device.py index 1daa704..8ebb6a9 100644 --- a/django_netjsonconfig/models/device.py +++ b/django_netjsonconfig/models/device.py @@ -14,6 +14,7 @@ from ..base import TimeStampedEditableModel from ..settings import BACKENDS +from ..validators import key_validator @python_2_unicode_compatible @@ -98,6 +99,7 @@ class BaseDevice(AbstractConfig): NetJSON DeviceConfiguration object """ key = models.CharField(max_length=64, unique=True, db_index=True, + validators=[key_validator], help_text=_('unique key that will be used to ' 'build the download URL')) diff --git a/django_netjsonconfig/tests/test_device.py b/django_netjsonconfig/tests/test_device.py index 3596ab7..2075f06 100644 --- a/django_netjsonconfig/tests/test_device.py +++ b/django_netjsonconfig/tests/test_device.py @@ -116,3 +116,19 @@ def test_m2m_validation(self): self.fail('ValidationError not raised') t.config['files'][0]['path'] = '/test2' d.templates.add(t) + + def test_key_validation(self): + d = Device(name='test', + backend='netjsonconfig.OpenWrt', + config={'general':{'hostname':'json-test'}}) + d.key = 'key/key' + with self.assertRaises(ValidationError): + d.full_clean() + d.key = 'key.key' + with self.assertRaises(ValidationError): + d.full_clean() + d.key = 'key key' + with self.assertRaises(ValidationError): + d.full_clean() + d.key = self.TEST_KEY + d.full_clean() diff --git a/django_netjsonconfig/validators.py b/django_netjsonconfig/validators.py new file mode 100644 index 0000000..1b475a6 --- /dev/null +++ b/django_netjsonconfig/validators.py @@ -0,0 +1,9 @@ +from django.core.validators import RegexValidator, _lazy_re_compile +from django.utils.translation import ugettext_lazy as _ + + +key_validator = RegexValidator( + _lazy_re_compile('^[^\s/\.]+$'), + message=_('Key must not contain spaces, dots or slashes.'), + code='invalid', +)