2018-02-16 03:25:26 -06:00
|
|
|
from extras.models import CustomField, CustomFieldChoice
|
|
|
|
|
|
|
|
from ruamel.yaml import YAML
|
2018-12-19 07:25:58 -06:00
|
|
|
from pathlib import Path
|
|
|
|
import sys
|
2018-02-16 03:25:26 -06:00
|
|
|
|
|
|
|
def get_class_for_class_path(class_path):
|
|
|
|
import importlib
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
|
|
|
|
|
|
|
module_name, class_name = class_path.rsplit(".", 1)
|
|
|
|
module = importlib.import_module(module_name)
|
|
|
|
clazz = getattr(module, class_name)
|
|
|
|
return ContentType.objects.get_for_model(clazz)
|
|
|
|
|
2018-12-19 07:25:58 -06:00
|
|
|
file = Path('/opt/netbox/initializers/custom_fields.yml')
|
|
|
|
if not file.is_file():
|
|
|
|
sys.exit()
|
|
|
|
|
|
|
|
with file.open('r') as stream:
|
2018-02-16 03:25:26 -06:00
|
|
|
yaml = YAML(typ='safe')
|
|
|
|
customfields = yaml.load(stream)
|
|
|
|
|
|
|
|
if customfields is not None:
|
|
|
|
for cf_name, cf_details in customfields.items():
|
|
|
|
custom_field, created = CustomField.objects.get_or_create(name = cf_name)
|
|
|
|
|
|
|
|
if created:
|
|
|
|
if cf_details.get('default', 0):
|
|
|
|
custom_field.default = cf_details['default']
|
|
|
|
|
|
|
|
if cf_details.get('description', 0):
|
|
|
|
custom_field.description = cf_details['description']
|
|
|
|
|
|
|
|
if cf_details.get('label', 0):
|
|
|
|
custom_field.label = cf_details['label']
|
|
|
|
|
|
|
|
for object_type in cf_details.get('on_objects', []):
|
|
|
|
custom_field.obj_type.add(get_class_for_class_path(object_type))
|
|
|
|
|
|
|
|
if cf_details.get('required', 0):
|
|
|
|
custom_field.required = cf_details['required']
|
|
|
|
|
|
|
|
if cf_details.get('type', 0):
|
2020-01-17 08:22:16 -06:00
|
|
|
custom_field.type = cf_details['type']
|
2018-02-16 03:25:26 -06:00
|
|
|
|
|
|
|
if cf_details.get('weight', 0):
|
|
|
|
custom_field.weight = cf_details['weight']
|
|
|
|
|
|
|
|
custom_field.save()
|
|
|
|
|
2018-04-18 11:51:04 -05:00
|
|
|
for idx, choice_details in enumerate(cf_details.get('choices', [])):
|
2018-05-18 14:24:31 -05:00
|
|
|
choice, _ = CustomFieldChoice.objects.get_or_create(
|
2018-02-16 03:25:26 -06:00
|
|
|
field=custom_field,
|
2018-04-18 11:51:04 -05:00
|
|
|
value=choice_details['value'],
|
2018-05-18 14:33:50 -05:00
|
|
|
defaults={'weight': idx * 10}
|
2018-04-18 11:51:04 -05:00
|
|
|
)
|
2018-02-16 03:25:26 -06:00
|
|
|
|
|
|
|
print("🔧 Created custom field", cf_name)
|