CustomField drop down in Custom Scripts

181 views
Skip to first unread message

Mahomed Hussein

unread,
May 28, 2020, 8:08:20 AM5/28/20
to NetBox
Hi

I have a custom field that is a list as shown in the screenshot, but I am struggling to make this a select list in a custom script. So far, with a lot of bashing away, I've managed to get to the point where I have this queryset using nbshell, but I am not sure how to translate that into a ChoiceVar or ObjectVar with APISelect

>>> field_vals
<QuerySet [<CustomFieldChoice: Live>, <CustomFieldChoice: Ops>, <CustomFieldChoice: UAT>, <CustomFieldChoice: Develop>, <CustomFieldChoice: Staging>]>


netbox_list.png




















I have also tried this code:

    content_type = ContentType.objects.get_for_model(VirtualMachine)
    custom_field = CustomField.objects.get(obj_type=content_type, name="Env")
cf_environment = ObjectVar(
        queryset = CustomFieldChoice.objects.filter(field=custom_field),
        label = 'Environment',
        widget = APISelect()
)


But I get this error:

The complete exception is provided below:
<class 'django.urls.exceptions.NoReverseMatch'>
Reverse for 'customfieldchoice-list' not found. 'customfieldchoice-list' is not a valid view function or pattern name.

Any help would be sincerely appreciated.

Mahomed Hussein

unread,
May 28, 2020, 12:37:12 PM5/28/20
to NetBox
Well, I've cobbled something together. I'm not sure it's the most elegant solution but it works.

    content_type = ContentType.objects.get_for_model(VirtualMachine)
    custom_fields = CustomField.objects.get(obj_type=content_type, name="Env")

    ENV_VALS = CustomFieldChoice.objects.filter(field=custom_fields).values()

    ENV_CHOICES = ()
    for val in ENV_VALS:
        ENV_CHOICES = ENV_CHOICES + ((f"{val['id']}", f"{val['value']}"),)

    cf_environment = ChoiceVar(
        choices=ENV_CHOICES,
        label="Environment",
        required=False
    )

    def run(self, data):

        vm = VirtualMachine(
            name=data["vm_name"],
        vm.save()

        content_type = ContentType.objects.get_for_model(VirtualMachine)
        custom_fields = CustomFieldValue.objects.filter(
            obj_type=content_type, obj_id=vm.id)

        cf_lastupdate = custom_fields.filter(field_id=1)
        cf_env = custom_fields.filter(field_id=5)
        cf_lastupdate.update_or_create(
            obj_id=vm.id, obj_type_id=80, field_id=1, serialized_value=data["cf_last_updated"])
        cf_env.update_or_create(obj_id=vm.id, obj_type_id=80,
                                field_id=5, serialized_value=data["cf_environment"])

        vm.save()



Please let me know if there's a better way of doing this (as I'm learning python as I'm learning Netbox). Thanks.
Reply all
Reply to author
Forward
0 new messages