customfields.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import re
  2. from datetime import datetime, date
  3. import django_filters
  4. from django import forms
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.contrib.postgres.fields import ArrayField
  7. from django.core.validators import RegexValidator, ValidationError
  8. from django.db import models
  9. from django.urls import reverse
  10. from django.utils.html import escape
  11. from django.utils.safestring import mark_safe
  12. from extras.choices import *
  13. from extras.utils import FeatureQuery, extras_features
  14. from netbox.models import ChangeLoggedModel
  15. from utilities import filters
  16. from utilities.forms import (
  17. CSVChoiceField, DatePicker, LaxURLField, StaticSelectMultiple, StaticSelect, add_blank_choice,
  18. )
  19. from utilities.querysets import RestrictedQuerySet
  20. from utilities.validators import validate_regex
  21. class CustomFieldManager(models.Manager.from_queryset(RestrictedQuerySet)):
  22. use_in_migrations = True
  23. def get_for_model(self, model):
  24. """
  25. Return all CustomFields assigned to the given model.
  26. """
  27. content_type = ContentType.objects.get_for_model(model._meta.concrete_model)
  28. return self.get_queryset().filter(content_types=content_type)
  29. @extras_features('webhooks', 'export_templates')
  30. class CustomField(ChangeLoggedModel):
  31. content_types = models.ManyToManyField(
  32. to=ContentType,
  33. related_name='custom_fields',
  34. limit_choices_to=FeatureQuery('custom_fields'),
  35. help_text='The object(s) to which this field applies.'
  36. )
  37. type = models.CharField(
  38. max_length=50,
  39. choices=CustomFieldTypeChoices,
  40. default=CustomFieldTypeChoices.TYPE_TEXT
  41. )
  42. name = models.CharField(
  43. max_length=50,
  44. unique=True,
  45. help_text='Internal field name'
  46. )
  47. label = models.CharField(
  48. max_length=50,
  49. blank=True,
  50. help_text='Name of the field as displayed to users (if not provided, '
  51. 'the field\'s name will be used)'
  52. )
  53. description = models.CharField(
  54. max_length=200,
  55. blank=True
  56. )
  57. required = models.BooleanField(
  58. default=False,
  59. help_text='If true, this field is required when creating new objects '
  60. 'or editing an existing object.'
  61. )
  62. filter_logic = models.CharField(
  63. max_length=50,
  64. choices=CustomFieldFilterLogicChoices,
  65. default=CustomFieldFilterLogicChoices.FILTER_LOOSE,
  66. help_text='Loose matches any instance of a given string; exact '
  67. 'matches the entire field.'
  68. )
  69. default = models.JSONField(
  70. blank=True,
  71. null=True,
  72. help_text='Default value for the field (must be a JSON value). Encapsulate '
  73. 'strings with double quotes (e.g. "Foo").'
  74. )
  75. weight = models.PositiveSmallIntegerField(
  76. default=100,
  77. help_text='Fields with higher weights appear lower in a form.'
  78. )
  79. validation_minimum = models.PositiveIntegerField(
  80. blank=True,
  81. null=True,
  82. verbose_name='Minimum value',
  83. help_text='Minimum allowed value (for numeric fields)'
  84. )
  85. validation_maximum = models.PositiveIntegerField(
  86. blank=True,
  87. null=True,
  88. verbose_name='Maximum value',
  89. help_text='Maximum allowed value (for numeric fields)'
  90. )
  91. validation_regex = models.CharField(
  92. blank=True,
  93. validators=[validate_regex],
  94. max_length=500,
  95. verbose_name='Validation regex',
  96. help_text='Regular expression to enforce on text field values. Use ^ and $ to force matching of entire string. '
  97. 'For example, <code>^[A-Z]{3}$</code> will limit values to exactly three uppercase letters.'
  98. )
  99. choices = ArrayField(
  100. base_field=models.CharField(max_length=100),
  101. blank=True,
  102. null=True,
  103. help_text='Comma-separated list of available choices (for selection fields)'
  104. )
  105. objects = CustomFieldManager()
  106. class Meta:
  107. ordering = ['weight', 'name']
  108. def __str__(self):
  109. return self.label or self.name.replace('_', ' ').capitalize()
  110. def get_absolute_url(self):
  111. return reverse('extras:customfield', args=[self.pk])
  112. def __init__(self, *args, **kwargs):
  113. super().__init__(*args, **kwargs)
  114. # Cache instance's original name so we can check later whether it has changed
  115. self._name = self.name
  116. def populate_initial_data(self, content_types):
  117. """
  118. Populate initial custom field data upon either a) the creation of a new CustomField, or
  119. b) the assignment of an existing CustomField to new object types.
  120. """
  121. for ct in content_types:
  122. model = ct.model_class()
  123. instances = model.objects.exclude(**{f'custom_field_data__contains': self.name})
  124. for instance in instances:
  125. instance.custom_field_data[self.name] = self.default
  126. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  127. def remove_stale_data(self, content_types):
  128. """
  129. Delete custom field data which is no longer relevant (either because the CustomField is
  130. no longer assigned to a model, or because it has been deleted).
  131. """
  132. for ct in content_types:
  133. model = ct.model_class()
  134. instances = model.objects.filter(**{f'custom_field_data__{self.name}__isnull': False})
  135. for instance in instances:
  136. del(instance.custom_field_data[self.name])
  137. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  138. def rename_object_data(self, old_name, new_name):
  139. """
  140. Called when a CustomField has been renamed. Updates all assigned object data.
  141. """
  142. for ct in self.content_types.all():
  143. model = ct.model_class()
  144. params = {f'custom_field_data__{old_name}__isnull': False}
  145. instances = model.objects.filter(**params)
  146. for instance in instances:
  147. instance.custom_field_data[new_name] = instance.custom_field_data.pop(old_name)
  148. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  149. def clean(self):
  150. super().clean()
  151. # Validate the field's default value (if any)
  152. if self.default is not None:
  153. try:
  154. if self.type in (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_LONGTEXT):
  155. default_value = str(self.default)
  156. else:
  157. default_value = self.default
  158. self.validate(default_value)
  159. except ValidationError as err:
  160. raise ValidationError({
  161. 'default': f'Invalid default value "{self.default}": {err.message}'
  162. })
  163. # Minimum/maximum values can be set only for numeric fields
  164. if self.validation_minimum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  165. raise ValidationError({
  166. 'validation_minimum': "A minimum value may be set only for numeric fields"
  167. })
  168. if self.validation_maximum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  169. raise ValidationError({
  170. 'validation_maximum': "A maximum value may be set only for numeric fields"
  171. })
  172. # Regex validation can be set only for text fields
  173. regex_types = (
  174. CustomFieldTypeChoices.TYPE_TEXT,
  175. CustomFieldTypeChoices.TYPE_LONGTEXT,
  176. CustomFieldTypeChoices.TYPE_URL,
  177. )
  178. if self.validation_regex and self.type not in regex_types:
  179. raise ValidationError({
  180. 'validation_regex': "Regular expression validation is supported only for text and URL fields"
  181. })
  182. # Choices can be set only on selection fields
  183. if self.choices and self.type not in (
  184. CustomFieldTypeChoices.TYPE_SELECT,
  185. CustomFieldTypeChoices.TYPE_MULTISELECT
  186. ):
  187. raise ValidationError({
  188. 'choices': "Choices may be set only for custom selection fields."
  189. })
  190. # A selection field must have at least two choices defined
  191. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.choices and len(self.choices) < 2:
  192. raise ValidationError({
  193. 'choices': "Selection fields must specify at least two choices."
  194. })
  195. # A selection field's default (if any) must be present in its available choices
  196. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.default and self.default not in self.choices:
  197. raise ValidationError({
  198. 'default': f"The specified default value ({self.default}) is not listed as an available choice."
  199. })
  200. def to_form_field(self, set_initial=True, enforce_required=True, for_csv_import=False):
  201. """
  202. Return a form field suitable for setting a CustomField's value for an object.
  203. set_initial: Set initial date for the field. This should be False when generating a field for bulk editing.
  204. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
  205. for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
  206. """
  207. initial = self.default if set_initial else None
  208. required = self.required if enforce_required else False
  209. # Integer
  210. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  211. field = forms.IntegerField(
  212. required=required,
  213. initial=initial,
  214. min_value=self.validation_minimum,
  215. max_value=self.validation_maximum
  216. )
  217. # Boolean
  218. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  219. choices = (
  220. (None, '---------'),
  221. (True, 'True'),
  222. (False, 'False'),
  223. )
  224. field = forms.NullBooleanField(
  225. required=required, initial=initial, widget=StaticSelect(choices=choices)
  226. )
  227. # Date
  228. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  229. field = forms.DateField(required=required, initial=initial, widget=DatePicker())
  230. # Select
  231. elif self.type in (CustomFieldTypeChoices.TYPE_SELECT, CustomFieldTypeChoices.TYPE_MULTISELECT):
  232. choices = [(c, c) for c in self.choices]
  233. default_choice = self.default if self.default in self.choices else None
  234. if not required or default_choice is None:
  235. choices = add_blank_choice(choices)
  236. # Set the initial value to the first available choice (if any)
  237. if set_initial and default_choice:
  238. initial = default_choice
  239. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  240. field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
  241. field = field_class(
  242. choices=choices, required=required, initial=initial, widget=StaticSelect()
  243. )
  244. else:
  245. field_class = CSVChoiceField if for_csv_import else forms.MultipleChoiceField
  246. field = field_class(
  247. choices=choices, required=required, initial=initial, widget=StaticSelectMultiple()
  248. )
  249. # URL
  250. elif self.type == CustomFieldTypeChoices.TYPE_URL:
  251. field = LaxURLField(required=required, initial=initial)
  252. # JSON
  253. elif self.type == CustomFieldTypeChoices.TYPE_JSON:
  254. field = forms.JSONField(required=required, initial=initial)
  255. # Text
  256. else:
  257. if self.type == CustomFieldTypeChoices.TYPE_LONGTEXT:
  258. max_length = None
  259. widget = forms.Textarea
  260. else:
  261. max_length = 255
  262. widget = None
  263. field = forms.CharField(max_length=max_length, required=required, initial=initial, widget=widget)
  264. if self.validation_regex:
  265. field.validators = [
  266. RegexValidator(
  267. regex=self.validation_regex,
  268. message=mark_safe(f"Values must match this regex: <code>{self.validation_regex}</code>")
  269. )
  270. ]
  271. field.model = self
  272. field.label = str(self)
  273. if self.description:
  274. field.help_text = escape(self.description)
  275. return field
  276. def to_filter(self, lookup_expr=None):
  277. """
  278. Return a django_filters Filter instance suitable for this field type.
  279. :param lookup_expr: Custom lookup expression (optional)
  280. """
  281. kwargs = {
  282. 'field_name': f'custom_field_data__{self.name}'
  283. }
  284. if lookup_expr is not None:
  285. kwargs['lookup_expr'] = lookup_expr
  286. # Text/URL
  287. if self.type in (
  288. CustomFieldTypeChoices.TYPE_TEXT,
  289. CustomFieldTypeChoices.TYPE_LONGTEXT,
  290. CustomFieldTypeChoices.TYPE_URL,
  291. ):
  292. filter_class = filters.MultiValueCharFilter
  293. if self.filter_logic == CustomFieldFilterLogicChoices.FILTER_LOOSE:
  294. kwargs['lookup_expr'] = 'icontains'
  295. # Integer
  296. elif self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  297. filter_class = filters.MultiValueNumberFilter
  298. # Boolean
  299. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  300. filter_class = django_filters.BooleanFilter
  301. # Date
  302. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  303. filter_class = filters.MultiValueDateFilter
  304. # Select
  305. elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
  306. filter_class = filters.MultiValueCharFilter
  307. # Multiselect
  308. elif self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  309. filter_class = filters.MultiValueCharFilter
  310. kwargs['lookup_expr'] = 'has_key'
  311. # Unsupported custom field type
  312. else:
  313. return None
  314. filter_instance = filter_class(**kwargs)
  315. filter_instance.custom_field = self
  316. return filter_instance
  317. def validate(self, value):
  318. """
  319. Validate a value according to the field's type validation rules.
  320. """
  321. if value not in [None, '']:
  322. # Validate text field
  323. if self.type in (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_LONGTEXT):
  324. if type(value) is not str:
  325. raise ValidationError(f"Value must be a string.")
  326. if self.validation_regex and not re.match(self.validation_regex, value):
  327. raise ValidationError(f"Value must match regex '{self.validation_regex}'")
  328. # Validate integer
  329. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  330. if type(value) is not int:
  331. raise ValidationError("Value must be an integer.")
  332. if self.validation_minimum is not None and value < self.validation_minimum:
  333. raise ValidationError(f"Value must be at least {self.validation_minimum}")
  334. if self.validation_maximum is not None and value > self.validation_maximum:
  335. raise ValidationError(f"Value must not exceed {self.validation_maximum}")
  336. # Validate boolean
  337. if self.type == CustomFieldTypeChoices.TYPE_BOOLEAN and value not in [True, False, 1, 0]:
  338. raise ValidationError("Value must be true or false.")
  339. # Validate date
  340. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  341. if type(value) is not date:
  342. try:
  343. datetime.strptime(value, '%Y-%m-%d')
  344. except ValueError:
  345. raise ValidationError("Date values must be in the format YYYY-MM-DD.")
  346. # Validate selected choice
  347. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  348. if value not in self.choices:
  349. raise ValidationError(
  350. f"Invalid choice ({value}). Available choices are: {', '.join(self.choices)}"
  351. )
  352. # Validate all selected choices
  353. if self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  354. if not set(value).issubset(self.choices):
  355. raise ValidationError(
  356. f"Invalid choice(s) ({', '.join(value)}). Available choices are: {', '.join(self.choices)}"
  357. )
  358. elif self.required:
  359. raise ValidationError("Required field cannot be empty.")