1 from extras.constants import CF_TYPE_TEXT, CF_TYPE_INTEGER, CF_TYPE_BOOLEAN, CF_TYPE_DATE, CF_TYPE_URL, CF_TYPE_SELECT
2 from extras.models import CustomField, CustomFieldChoice
4 from ruamel.yaml import YAML
7 'boolean': CF_TYPE_BOOLEAN,
9 'integer': CF_TYPE_INTEGER,
10 'selection': CF_TYPE_SELECT,
15 def get_class_for_class_path(class_path):
17 from django.contrib.contenttypes.models import ContentType
19 module_name, class_name = class_path.rsplit(".", 1)
20 module = importlib.import_module(module_name)
21 clazz = getattr(module, class_name)
22 return ContentType.objects.get_for_model(clazz)
24 with open('/opt/netbox/initializers/custom_fields.yml', 'r') as stream:
25 yaml = YAML(typ='safe')
26 customfields = yaml.load(stream)
28 if customfields is not None:
29 for cf_name, cf_details in customfields.items():
30 custom_field, created = CustomField.objects.get_or_create(name = cf_name)
33 if cf_details.get('default', 0):
34 custom_field.default = cf_details['default']
36 if cf_details.get('description', 0):
37 custom_field.description = cf_details['description']
39 if cf_details.get('filterable', 0):
40 custom_field.is_filterables = cf_details['filterable']
42 if cf_details.get('label', 0):
43 custom_field.label = cf_details['label']
45 for object_type in cf_details.get('on_objects', []):
46 custom_field.obj_type.add(get_class_for_class_path(object_type))
48 if cf_details.get('required', 0):
49 custom_field.required = cf_details['required']
51 if cf_details.get('type', 0):
52 custom_field.type = text_to_fields[cf_details['type']]
54 if cf_details.get('weight', 0):
55 custom_field.weight = cf_details['weight']
59 for choice_details in cf_details.get('choices', []):
60 choice = CustomFieldChoice.objects.create(
62 value=choice_details['value'])
64 if choice_details.get('weight', 0):
65 choice.weight = choice_details['weight']
68 print("🔧 Created custom field", cf_name)