customfields.py 14 KB

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