From 3d6baeaab02f4e1e35c62062dbd6b3df2de48489 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Wed, 11 Nov 2020 15:24:39 -0500 Subject: [PATCH] Move selection field validation from admin form to model --- netbox/extras/admin.py | 8 -------- netbox/extras/models/customfields.py | 8 +++++++- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/netbox/extras/admin.py b/netbox/extras/admin.py index a0839b78d..8c0855719 100644 --- a/netbox/extras/admin.py +++ b/netbox/extras/admin.py @@ -89,14 +89,6 @@ class CustomFieldForm(forms.ModelForm): order_content_types(self.fields['content_types']) - def clean(self): - - # Validate selection choices - if self.cleaned_data['type'] == CustomFieldTypeChoices.TYPE_SELECT and len(self.cleaned_data['choices']) < 2: - raise forms.ValidationError({ - 'choices': 'Selection fields must specify at least two choices.' - }) - @admin.register(CustomField) class CustomFieldAdmin(admin.ModelAdmin): diff --git a/netbox/extras/models/customfields.py b/netbox/extras/models/customfields.py index 2fce1f6ce..203d58cd3 100644 --- a/netbox/extras/models/customfields.py +++ b/netbox/extras/models/customfields.py @@ -170,7 +170,13 @@ class CustomField(models.Model): # Choices can be set only on selection fields if self.choices and self.type != CustomFieldTypeChoices.TYPE_SELECT: raise ValidationError({ - 'choices': "Choices may be set only for selection-type custom fields." + 'choices': "Choices may be set only for custom selection fields." + }) + + # A selection field must have at least two choices defined + if self.type == CustomFieldTypeChoices.TYPE_SELECT and len(self.choices) < 2: + raise ValidationError({ + 'choices': "Selection fields must specify at least two choices." }) # A selection field's default (if any) must be present in its available choices