Skip to content
This repository has been archived by the owner on Jul 9, 2020. It is now read-only.

Commit

Permalink
Added key_validator to validate key field
Browse files Browse the repository at this point in the history
  • Loading branch information
nemesifier committed Dec 14, 2015
1 parent 99244a0 commit 46c1582
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions django_netjsonconfig/models/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from ..base import TimeStampedEditableModel
from ..settings import BACKENDS
from ..validators import key_validator


@python_2_unicode_compatible
Expand Down Expand Up @@ -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'))

Expand Down
16 changes: 16 additions & 0 deletions django_netjsonconfig/tests/test_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
9 changes: 9 additions & 0 deletions django_netjsonconfig/validators.py
Original file line number Diff line number Diff line change
@@ -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',
)

0 comments on commit 46c1582

Please sign in to comment.