customfields.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. import re
  2. from datetime import datetime, date
  3. import decimal
  4. import django_filters
  5. from django import forms
  6. from django.conf import settings
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.postgres.fields import ArrayField
  9. from django.core.validators import RegexValidator, ValidationError
  10. from django.db import models
  11. from django.urls import reverse
  12. from django.utils.html import escape
  13. from django.utils.safestring import mark_safe
  14. from django.utils.translation import gettext as _
  15. from extras.choices import *
  16. from extras.utils import FeatureQuery
  17. from netbox.models import ChangeLoggedModel
  18. from netbox.models.features import CloningMixin, ExportTemplatesMixin, WebhooksMixin
  19. from netbox.search import FieldTypes
  20. from utilities import filters
  21. from utilities.forms.fields import (
  22. CSVChoiceField, CSVModelChoiceField, CSVModelMultipleChoiceField, CSVMultipleChoiceField, DynamicModelChoiceField,
  23. DynamicModelMultipleChoiceField, JSONField, LaxURLField,
  24. )
  25. from utilities.forms.widgets import DatePicker, StaticSelectMultiple, StaticSelect
  26. from utilities.forms.utils import add_blank_choice
  27. from utilities.querysets import RestrictedQuerySet
  28. from utilities.validators import validate_regex
  29. __all__ = (
  30. 'CustomField',
  31. 'CustomFieldManager',
  32. )
  33. SEARCH_TYPES = {
  34. CustomFieldTypeChoices.TYPE_TEXT: FieldTypes.STRING,
  35. CustomFieldTypeChoices.TYPE_LONGTEXT: FieldTypes.STRING,
  36. CustomFieldTypeChoices.TYPE_INTEGER: FieldTypes.INTEGER,
  37. CustomFieldTypeChoices.TYPE_DECIMAL: FieldTypes.FLOAT,
  38. CustomFieldTypeChoices.TYPE_DATE: FieldTypes.STRING,
  39. CustomFieldTypeChoices.TYPE_URL: FieldTypes.STRING,
  40. }
  41. class CustomFieldManager(models.Manager.from_queryset(RestrictedQuerySet)):
  42. use_in_migrations = True
  43. def get_for_model(self, model):
  44. """
  45. Return all CustomFields assigned to the given model.
  46. """
  47. content_type = ContentType.objects.get_for_model(model._meta.concrete_model)
  48. return self.get_queryset().filter(content_types=content_type)
  49. class CustomField(CloningMixin, ExportTemplatesMixin, WebhooksMixin, ChangeLoggedModel):
  50. content_types = models.ManyToManyField(
  51. to=ContentType,
  52. related_name='custom_fields',
  53. limit_choices_to=FeatureQuery('custom_fields'),
  54. help_text=_('The object(s) to which this field applies.')
  55. )
  56. type = models.CharField(
  57. max_length=50,
  58. choices=CustomFieldTypeChoices,
  59. default=CustomFieldTypeChoices.TYPE_TEXT,
  60. help_text=_('The type of data this custom field holds')
  61. )
  62. object_type = models.ForeignKey(
  63. to=ContentType,
  64. on_delete=models.PROTECT,
  65. blank=True,
  66. null=True,
  67. help_text=_('The type of NetBox object this field maps to (for object fields)')
  68. )
  69. name = models.CharField(
  70. max_length=50,
  71. unique=True,
  72. help_text=_('Internal field name'),
  73. validators=(
  74. RegexValidator(
  75. regex=r'^[a-z0-9_]+$',
  76. message="Only alphanumeric characters and underscores are allowed.",
  77. flags=re.IGNORECASE
  78. ),
  79. )
  80. )
  81. label = models.CharField(
  82. max_length=50,
  83. blank=True,
  84. help_text=_('Name of the field as displayed to users (if not provided, '
  85. 'the field\'s name will be used)')
  86. )
  87. group_name = models.CharField(
  88. max_length=50,
  89. blank=True,
  90. help_text=_("Custom fields within the same group will be displayed together")
  91. )
  92. description = models.CharField(
  93. max_length=200,
  94. blank=True
  95. )
  96. required = models.BooleanField(
  97. default=False,
  98. help_text=_('If true, this field is required when creating new objects '
  99. 'or editing an existing object.')
  100. )
  101. search_weight = models.PositiveSmallIntegerField(
  102. default=1000,
  103. help_text=_('Weighting for search. Lower values are considered more important. '
  104. 'Fields with a search weight of zero will be ignored.')
  105. )
  106. filter_logic = models.CharField(
  107. max_length=50,
  108. choices=CustomFieldFilterLogicChoices,
  109. default=CustomFieldFilterLogicChoices.FILTER_LOOSE,
  110. help_text=_('Loose matches any instance of a given string; exact '
  111. 'matches the entire field.')
  112. )
  113. default = models.JSONField(
  114. blank=True,
  115. null=True,
  116. help_text=_('Default value for the field (must be a JSON value). Encapsulate '
  117. 'strings with double quotes (e.g. "Foo").')
  118. )
  119. weight = models.PositiveSmallIntegerField(
  120. default=100,
  121. verbose_name='Display weight',
  122. help_text=_('Fields with higher weights appear lower in a form.')
  123. )
  124. validation_minimum = models.IntegerField(
  125. blank=True,
  126. null=True,
  127. verbose_name='Minimum value',
  128. help_text=_('Minimum allowed value (for numeric fields)')
  129. )
  130. validation_maximum = models.IntegerField(
  131. blank=True,
  132. null=True,
  133. verbose_name='Maximum value',
  134. help_text=_('Maximum allowed value (for numeric fields)')
  135. )
  136. validation_regex = models.CharField(
  137. blank=True,
  138. validators=[validate_regex],
  139. max_length=500,
  140. verbose_name='Validation regex',
  141. help_text=_('Regular expression to enforce on text field values. Use ^ and $ to force matching of entire string. '
  142. 'For example, <code>^[A-Z]{3}$</code> will limit values to exactly three uppercase letters.')
  143. )
  144. choices = ArrayField(
  145. base_field=models.CharField(max_length=100),
  146. blank=True,
  147. null=True,
  148. help_text=_('Comma-separated list of available choices (for selection fields)')
  149. )
  150. ui_visibility = models.CharField(
  151. max_length=50,
  152. choices=CustomFieldVisibilityChoices,
  153. default=CustomFieldVisibilityChoices.VISIBILITY_READ_WRITE,
  154. verbose_name='UI visibility',
  155. help_text=_('Specifies the visibility of custom field in the UI')
  156. )
  157. objects = CustomFieldManager()
  158. clone_fields = (
  159. 'content_types', 'type', 'object_type', 'group_name', 'description', 'required', 'search_weight',
  160. 'filter_logic', 'default', 'weight', 'validation_minimum', 'validation_maximum', 'validation_regex', 'choices',
  161. 'ui_visibility',
  162. )
  163. class Meta:
  164. ordering = ['group_name', 'weight', 'name']
  165. def __str__(self):
  166. return self.label or self.name.replace('_', ' ').capitalize()
  167. def get_absolute_url(self):
  168. return reverse('extras:customfield', args=[self.pk])
  169. @property
  170. def docs_url(self):
  171. return f'{settings.STATIC_URL}docs/models/extras/customfield/'
  172. def __init__(self, *args, **kwargs):
  173. super().__init__(*args, **kwargs)
  174. # Cache instance's original name so we can check later whether it has changed
  175. self._name = self.name
  176. @property
  177. def search_type(self):
  178. return SEARCH_TYPES.get(self.type)
  179. def populate_initial_data(self, content_types):
  180. """
  181. Populate initial custom field data upon either a) the creation of a new CustomField, or
  182. b) the assignment of an existing CustomField to new object types.
  183. """
  184. for ct in content_types:
  185. model = ct.model_class()
  186. instances = model.objects.exclude(**{f'custom_field_data__contains': self.name})
  187. for instance in instances:
  188. instance.custom_field_data[self.name] = self.default
  189. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  190. def remove_stale_data(self, content_types):
  191. """
  192. Delete custom field data which is no longer relevant (either because the CustomField is
  193. no longer assigned to a model, or because it has been deleted).
  194. """
  195. for ct in content_types:
  196. model = ct.model_class()
  197. instances = model.objects.filter(**{f'custom_field_data__{self.name}__isnull': False})
  198. for instance in instances:
  199. del instance.custom_field_data[self.name]
  200. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  201. def rename_object_data(self, old_name, new_name):
  202. """
  203. Called when a CustomField has been renamed. Updates all assigned object data.
  204. """
  205. for ct in self.content_types.all():
  206. model = ct.model_class()
  207. params = {f'custom_field_data__{old_name}__isnull': False}
  208. instances = model.objects.filter(**params)
  209. for instance in instances:
  210. instance.custom_field_data[new_name] = instance.custom_field_data.pop(old_name)
  211. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  212. def clean(self):
  213. super().clean()
  214. # Validate the field's default value (if any)
  215. if self.default is not None:
  216. try:
  217. if self.type in (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_LONGTEXT):
  218. default_value = str(self.default)
  219. else:
  220. default_value = self.default
  221. self.validate(default_value)
  222. except ValidationError as err:
  223. raise ValidationError({
  224. 'default': f'Invalid default value "{self.default}": {err.message}'
  225. })
  226. # Minimum/maximum values can be set only for numeric fields
  227. if self.type not in (CustomFieldTypeChoices.TYPE_INTEGER, CustomFieldTypeChoices.TYPE_DECIMAL):
  228. if self.validation_minimum:
  229. raise ValidationError({'validation_minimum': "A minimum value may be set only for numeric fields"})
  230. if self.validation_maximum:
  231. raise ValidationError({'validation_maximum': "A maximum value may be set only for numeric fields"})
  232. # Regex validation can be set only for text fields
  233. regex_types = (
  234. CustomFieldTypeChoices.TYPE_TEXT,
  235. CustomFieldTypeChoices.TYPE_LONGTEXT,
  236. CustomFieldTypeChoices.TYPE_URL,
  237. )
  238. if self.validation_regex and self.type not in regex_types:
  239. raise ValidationError({
  240. 'validation_regex': "Regular expression validation is supported only for text and URL fields"
  241. })
  242. # Choices can be set only on selection fields
  243. if self.choices and self.type not in (
  244. CustomFieldTypeChoices.TYPE_SELECT,
  245. CustomFieldTypeChoices.TYPE_MULTISELECT
  246. ):
  247. raise ValidationError({
  248. 'choices': "Choices may be set only for custom selection fields."
  249. })
  250. # Selection fields must have at least one choice defined
  251. if self.type in (
  252. CustomFieldTypeChoices.TYPE_SELECT,
  253. CustomFieldTypeChoices.TYPE_MULTISELECT
  254. ) and not self.choices:
  255. raise ValidationError({
  256. 'choices': "Selection fields must specify at least one choice."
  257. })
  258. # A selection field's default (if any) must be present in its available choices
  259. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.default and self.default not in self.choices:
  260. raise ValidationError({
  261. 'default': f"The specified default value ({self.default}) is not listed as an available choice."
  262. })
  263. # Object fields must define an object_type; other fields must not
  264. if self.type in (CustomFieldTypeChoices.TYPE_OBJECT, CustomFieldTypeChoices.TYPE_MULTIOBJECT):
  265. if not self.object_type:
  266. raise ValidationError({
  267. 'object_type': "Object fields must define an object type."
  268. })
  269. elif self.object_type:
  270. raise ValidationError({
  271. 'object_type': f"{self.get_type_display()} fields may not define an object type."
  272. })
  273. def serialize(self, value):
  274. """
  275. Prepare a value for storage as JSON data.
  276. """
  277. if value is None:
  278. return value
  279. if self.type == CustomFieldTypeChoices.TYPE_DATE and type(value) is date:
  280. return value.isoformat()
  281. if self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  282. return value.pk
  283. if self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  284. return [obj.pk for obj in value] or None
  285. return value
  286. def deserialize(self, value):
  287. """
  288. Convert JSON data to a Python object suitable for the field type.
  289. """
  290. if value is None:
  291. return value
  292. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  293. try:
  294. return date.fromisoformat(value)
  295. except ValueError:
  296. return value
  297. if self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  298. model = self.object_type.model_class()
  299. return model.objects.filter(pk=value).first()
  300. if self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  301. model = self.object_type.model_class()
  302. return model.objects.filter(pk__in=value)
  303. return value
  304. def to_form_field(self, set_initial=True, enforce_required=True, enforce_visibility=True, for_csv_import=False):
  305. """
  306. Return a form field suitable for setting a CustomField's value for an object.
  307. set_initial: Set initial data for the field. This should be False when generating a field for bulk editing.
  308. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
  309. enforce_visibility: Honor the value of CustomField.ui_visibility. Set to False for filtering.
  310. for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
  311. """
  312. initial = self.default if set_initial else None
  313. required = self.required if enforce_required else False
  314. # Integer
  315. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  316. field = forms.IntegerField(
  317. required=required,
  318. initial=initial,
  319. min_value=self.validation_minimum,
  320. max_value=self.validation_maximum
  321. )
  322. # Decimal
  323. elif self.type == CustomFieldTypeChoices.TYPE_DECIMAL:
  324. field = forms.DecimalField(
  325. required=required,
  326. initial=initial,
  327. max_digits=12,
  328. decimal_places=4,
  329. min_value=self.validation_minimum,
  330. max_value=self.validation_maximum
  331. )
  332. # Boolean
  333. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  334. choices = (
  335. (None, '---------'),
  336. (True, 'True'),
  337. (False, 'False'),
  338. )
  339. field = forms.NullBooleanField(
  340. required=required, initial=initial, widget=StaticSelect(choices=choices)
  341. )
  342. # Date
  343. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  344. field = forms.DateField(required=required, initial=initial, widget=DatePicker())
  345. # Select
  346. elif self.type in (CustomFieldTypeChoices.TYPE_SELECT, CustomFieldTypeChoices.TYPE_MULTISELECT):
  347. choices = [(c, c) for c in self.choices]
  348. default_choice = self.default if self.default in self.choices else None
  349. if not required or default_choice is None:
  350. choices = add_blank_choice(choices)
  351. # Set the initial value to the first available choice (if any)
  352. if set_initial and default_choice:
  353. initial = default_choice
  354. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  355. field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
  356. field = field_class(
  357. choices=choices, required=required, initial=initial, widget=StaticSelect()
  358. )
  359. else:
  360. field_class = CSVMultipleChoiceField if for_csv_import else forms.MultipleChoiceField
  361. field = field_class(
  362. choices=choices, required=required, initial=initial, widget=StaticSelectMultiple()
  363. )
  364. # URL
  365. elif self.type == CustomFieldTypeChoices.TYPE_URL:
  366. field = LaxURLField(required=required, initial=initial)
  367. # JSON
  368. elif self.type == CustomFieldTypeChoices.TYPE_JSON:
  369. field = JSONField(required=required, initial=initial)
  370. # Object
  371. elif self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  372. model = self.object_type.model_class()
  373. field_class = CSVModelChoiceField if for_csv_import else DynamicModelChoiceField
  374. field = field_class(
  375. queryset=model.objects.all(),
  376. required=required,
  377. initial=initial
  378. )
  379. # Multiple objects
  380. elif self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  381. model = self.object_type.model_class()
  382. field_class = CSVModelMultipleChoiceField if for_csv_import else DynamicModelMultipleChoiceField
  383. field = field_class(
  384. queryset=model.objects.all(),
  385. required=required,
  386. initial=initial,
  387. )
  388. # Text
  389. else:
  390. widget = forms.Textarea if self.type == CustomFieldTypeChoices.TYPE_LONGTEXT else None
  391. field = forms.CharField(required=required, initial=initial, widget=widget)
  392. if self.validation_regex:
  393. field.validators = [
  394. RegexValidator(
  395. regex=self.validation_regex,
  396. message=mark_safe(f"Values must match this regex: <code>{self.validation_regex}</code>")
  397. )
  398. ]
  399. field.model = self
  400. field.label = str(self)
  401. if self.description:
  402. field.help_text = escape(self.description)
  403. # Annotate read-only fields
  404. if enforce_visibility and self.ui_visibility == CustomFieldVisibilityChoices.VISIBILITY_READ_ONLY:
  405. field.disabled = True
  406. prepend = '<br />' if field.help_text else ''
  407. field.help_text += f'{prepend}<i class="mdi mdi-alert-circle-outline"></i> Field is set to read-only.'
  408. return field
  409. def to_filter(self, lookup_expr=None):
  410. """
  411. Return a django_filters Filter instance suitable for this field type.
  412. :param lookup_expr: Custom lookup expression (optional)
  413. """
  414. kwargs = {
  415. 'field_name': f'custom_field_data__{self.name}'
  416. }
  417. if lookup_expr is not None:
  418. kwargs['lookup_expr'] = lookup_expr
  419. # Text/URL
  420. if self.type in (
  421. CustomFieldTypeChoices.TYPE_TEXT,
  422. CustomFieldTypeChoices.TYPE_LONGTEXT,
  423. CustomFieldTypeChoices.TYPE_URL,
  424. ):
  425. filter_class = filters.MultiValueCharFilter
  426. if self.filter_logic == CustomFieldFilterLogicChoices.FILTER_LOOSE:
  427. kwargs['lookup_expr'] = 'icontains'
  428. # Integer
  429. elif self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  430. filter_class = filters.MultiValueNumberFilter
  431. # Decimal
  432. elif self.type == CustomFieldTypeChoices.TYPE_DECIMAL:
  433. filter_class = filters.MultiValueDecimalFilter
  434. # Boolean
  435. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  436. filter_class = django_filters.BooleanFilter
  437. # Date
  438. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  439. filter_class = filters.MultiValueDateFilter
  440. # Select
  441. elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
  442. filter_class = filters.MultiValueCharFilter
  443. # Multiselect
  444. elif self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  445. filter_class = filters.MultiValueCharFilter
  446. kwargs['lookup_expr'] = 'has_key'
  447. # Object
  448. elif self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  449. filter_class = filters.MultiValueNumberFilter
  450. # Multi-object
  451. elif self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  452. filter_class = filters.MultiValueNumberFilter
  453. kwargs['lookup_expr'] = 'contains'
  454. # Unsupported custom field type
  455. else:
  456. return None
  457. filter_instance = filter_class(**kwargs)
  458. filter_instance.custom_field = self
  459. return filter_instance
  460. def validate(self, value):
  461. """
  462. Validate a value according to the field's type validation rules.
  463. """
  464. if value not in [None, '']:
  465. # Validate text field
  466. if self.type in (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_LONGTEXT):
  467. if type(value) is not str:
  468. raise ValidationError(f"Value must be a string.")
  469. if self.validation_regex and not re.match(self.validation_regex, value):
  470. raise ValidationError(f"Value must match regex '{self.validation_regex}'")
  471. # Validate integer
  472. elif self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  473. if type(value) is not int:
  474. raise ValidationError("Value must be an integer.")
  475. if self.validation_minimum is not None and value < self.validation_minimum:
  476. raise ValidationError(f"Value must be at least {self.validation_minimum}")
  477. if self.validation_maximum is not None and value > self.validation_maximum:
  478. raise ValidationError(f"Value must not exceed {self.validation_maximum}")
  479. # Validate decimal
  480. elif self.type == CustomFieldTypeChoices.TYPE_DECIMAL:
  481. try:
  482. decimal.Decimal(value)
  483. except decimal.InvalidOperation:
  484. raise ValidationError("Value must be a decimal.")
  485. if self.validation_minimum is not None and value < self.validation_minimum:
  486. raise ValidationError(f"Value must be at least {self.validation_minimum}")
  487. if self.validation_maximum is not None and value > self.validation_maximum:
  488. raise ValidationError(f"Value must not exceed {self.validation_maximum}")
  489. # Validate boolean
  490. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN and value not in [True, False, 1, 0]:
  491. raise ValidationError("Value must be true or false.")
  492. # Validate date
  493. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  494. if type(value) is not date:
  495. try:
  496. datetime.strptime(value, '%Y-%m-%d')
  497. except ValueError:
  498. raise ValidationError("Date values must be in the format YYYY-MM-DD.")
  499. # Validate selected choice
  500. elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
  501. if value not in self.choices:
  502. raise ValidationError(
  503. f"Invalid choice ({value}). Available choices are: {', '.join(self.choices)}"
  504. )
  505. # Validate all selected choices
  506. elif self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  507. if not set(value).issubset(self.choices):
  508. raise ValidationError(
  509. f"Invalid choice(s) ({', '.join(value)}). Available choices are: {', '.join(self.choices)}"
  510. )
  511. elif self.required:
  512. raise ValidationError("Required field cannot be empty.")