From 3e9cec3e8e1a3cbacbe651af6fdb2477c53d9f13 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Fri, 29 Jun 2018 16:01:28 -0400 Subject: [PATCH] Closes #2159: Allow custom choice field to specify a default choice --- netbox/extras/forms.py | 10 +++++++++- netbox/extras/migrations/0007_unicode_literals.py | 2 +- netbox/extras/models.py | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/netbox/extras/forms.py b/netbox/extras/forms.py index a923ae596..55f8435d6 100644 --- a/netbox/extras/forms.py +++ b/netbox/extras/forms.py @@ -4,6 +4,7 @@ from collections import OrderedDict from django import forms from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import ObjectDoesNotExist from utilities.forms import BootstrapMixin, BulkEditForm, LaxURLField from .constants import CF_FILTER_DISABLED, CF_TYPE_BOOLEAN, CF_TYPE_DATE, CF_TYPE_INTEGER, CF_TYPE_SELECT, CF_TYPE_URL @@ -53,7 +54,14 @@ def get_custom_fields_for_model(content_type, filterable_only=False, bulk_edit=F choices = [(cfc.pk, cfc) for cfc in cf.choices.all()] if not cf.required or bulk_edit or filterable_only: choices = [(None, '---------')] + choices - field = forms.TypedChoiceField(choices=choices, coerce=int, required=cf.required) + # Check for a default choice + default_choice = None + if initial: + try: + default_choice = cf.choices.get(value=initial).pk + except ObjectDoesNotExist: + pass + field = forms.TypedChoiceField(choices=choices, coerce=int, required=cf.required, initial=default_choice) # URL elif cf.type == CF_TYPE_URL: diff --git a/netbox/extras/migrations/0007_unicode_literals.py b/netbox/extras/migrations/0007_unicode_literals.py index c9a624510..cda07583f 100644 --- a/netbox/extras/migrations/0007_unicode_literals.py +++ b/netbox/extras/migrations/0007_unicode_literals.py @@ -16,7 +16,7 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='customfield', name='default', - field=models.CharField(blank=True, help_text='Default value for the field. Use "true" or "false" for booleans. N/A for selection fields.', max_length=100), + field=models.CharField(blank=True, help_text='Default value for the field. Use "true" or "false" for booleans.', max_length=100), ), migrations.AlterField( model_name='customfield', diff --git a/netbox/extras/models.py b/netbox/extras/models.py index 75945adcd..cb68f0e0d 100644 --- a/netbox/extras/models.py +++ b/netbox/extras/models.py @@ -91,7 +91,7 @@ class CustomField(models.Model): default = models.CharField( max_length=100, blank=True, - help_text='Default value for the field. Use "true" or "false" for booleans. N/A for selection fields.' + help_text='Default value for the field. Use "true" or "false" for booleans.' ) weight = models.PositiveSmallIntegerField( default=100,