Skip to content

Commit 21f4761

Browse files
12468 disallow double underscores in custom field names (#12523)
* 12468 disallow double underscores in custom field names * 12468 disallow double underscores in custom field names * 12468 review changes * 12468 correct migration * 12468 use inverse match * 12468 use inverse match * Add test for invalid custom field names --------- Co-authored-by: jeremystretch <[email protected]>
1 parent 39fd64b commit 21f4761

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

netbox/extras/migrations/0066_customfield_name_validation.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,22 @@ class Migration(migrations.Migration):
1313
migrations.AlterField(
1414
model_name='customfield',
1515
name='name',
16-
field=models.CharField(max_length=50, unique=True, validators=[django.core.validators.RegexValidator(flags=re.RegexFlag['IGNORECASE'], message='Only alphanumeric characters and underscores are allowed.', regex='^[a-z0-9_]+$')]),
16+
field=models.CharField(
17+
max_length=50,
18+
unique=True,
19+
validators=[
20+
django.core.validators.RegexValidator(
21+
flags=re.RegexFlag['IGNORECASE'],
22+
message='Only alphanumeric characters and underscores are allowed.',
23+
regex='^[a-z0-9_]+$',
24+
),
25+
django.core.validators.RegexValidator(
26+
flags=re.RegexFlag['IGNORECASE'],
27+
inverse_match=True,
28+
message='Double underscores are not permitted in custom field names.',
29+
regex=r'__',
30+
),
31+
],
32+
),
1733
),
1834
]

netbox/extras/models/customfields.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,12 @@ class CustomField(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
8585
message="Only alphanumeric characters and underscores are allowed.",
8686
flags=re.IGNORECASE
8787
),
88+
RegexValidator(
89+
regex=r'__',
90+
message="Double underscores are not permitted in custom field names.",
91+
flags=re.IGNORECASE,
92+
inverse_match=True
93+
),
8894
)
8995
)
9096
label = models.CharField(

netbox/extras/tests/test_customfields.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,17 @@ def setUpTestData(cls):
2929

3030
cls.object_type = ContentType.objects.get_for_model(Site)
3131

32+
def test_invalid_name(self):
33+
"""
34+
Try creating a CustomField with an invalid name.
35+
"""
36+
with self.assertRaises(ValidationError):
37+
# Invalid character
38+
CustomField(name='?', type=CustomFieldTypeChoices.TYPE_TEXT).full_clean()
39+
with self.assertRaises(ValidationError):
40+
# Double underscores not permitted
41+
CustomField(name='foo__bar', type=CustomFieldTypeChoices.TYPE_TEXT).full_clean()
42+
3243
def test_text_field(self):
3344
value = 'Foobar!'
3445

0 commit comments

Comments
 (0)