Merge "[UUI] Service Mesh Compliance for UUI"
[oom.git] / kubernetes / contrib / components / netbox / components / netbox-app / resources / config / startup_scripts / 20_custom_fields.py
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
3
4 from ruamel.yaml import YAML
5
6 text_to_fields = {
7   'boolean': CF_TYPE_BOOLEAN,
8   'date': CF_TYPE_DATE,
9   'integer': CF_TYPE_INTEGER,
10   'selection': CF_TYPE_SELECT,
11   'text': CF_TYPE_TEXT,
12   'url': CF_TYPE_URL,
13 }
14
15 def get_class_for_class_path(class_path):
16   import importlib
17   from django.contrib.contenttypes.models import ContentType
18
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)
23
24 with open('/opt/netbox/initializers/custom_fields.yml', 'r') as stream:
25   yaml = YAML(typ='safe')
26   customfields = yaml.load(stream)
27
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)
31
32       if created:
33         if cf_details.get('default', 0):
34           custom_field.default = cf_details['default']
35
36         if cf_details.get('description', 0):
37           custom_field.description = cf_details['description']
38
39         if cf_details.get('filterable', 0):
40           custom_field.is_filterables = cf_details['filterable']
41
42         if cf_details.get('label', 0):
43           custom_field.label = cf_details['label']
44
45         for object_type in cf_details.get('on_objects', []):
46           custom_field.obj_type.add(get_class_for_class_path(object_type))
47
48         if cf_details.get('required', 0):
49           custom_field.required = cf_details['required']
50
51         if cf_details.get('type', 0):
52           custom_field.type = text_to_fields[cf_details['type']]
53
54         if cf_details.get('weight', 0):
55           custom_field.weight = cf_details['weight']
56
57         custom_field.save()
58
59         for choice_details in cf_details.get('choices', []):
60           choice = CustomFieldChoice.objects.create(
61             field=custom_field,
62             value=choice_details['value'])
63
64           if choice_details.get('weight', 0):
65             choice.weight = choice_details['weight']
66             choice.save()
67
68         print("🔧 Created custom field", cf_name)